本题要求编写程序,计算 2 个有理数的和、差、积、商。
输入格式:
输入在一行中按照 a1/b1 a2/b2
的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为 0。
输出格式:
分别在 4 行中按照 有理数1 运算符 有理数2 = 结果
的格式顺序输出 2 个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式 k a/b
,其中 k
是整数部分,a/b
是最简分数部分;若为负数,则须加括号;若除法分母为 0,则输出 Inf
。题目保证正确的输出中没有超过整型范围的整数。
输入样例 1:
2/3 -4/2
输出样例 1:
5/3 0/6
输入样例 2:
5/3 0/6
输出样例 2:
1 2/3 + 0 = 1 2/3 1 2/3 - 0 = 1 2/3 1 2/3 * 0 = 0 1 2/3 / 0 = Inf
思路:
测试点2、3运行时错误:a1,b1,a2,b2的类型应该定义为long long,此时s1、s2数组的长度也应相应增大
运行时错误应该首先检查数组是否越界
代码:
#include<stdio.h> #include<iostream> #include<algorithm> #include<stdlib.h> using namespace std; struct Fraction{ long long up,down; Fraction(long long up, long long down):up(up),down(down){}; Fraction(){}; }; long long gcd(long long a, long long b){ if(b==0){ return a; } gcd(b,a%b); } Fraction reduction(Fraction fraction){//化简 if(fraction.down < 0){ fraction.down = - fraction.down; fraction.up = - fraction.up; } if(fraction.up == 0){ fraction.down = 1; }else{ long long d = gcd(abs(fraction.up), abs(fraction.down)); fraction.up /= d; fraction.down /= d; } return fraction; } void show(Fraction fraction){ fraction = reduction(fraction); if(fraction.up < 0){ cout<<"("; } if(fraction.down == 1){//整数 cout<<fraction.up; } else if(abs(fraction.up) > abs(fraction.down)){ //假分数 cout<<fraction.up/fraction.down<<" "<<abs(fraction.up) % abs(fraction.down)<<"/"<<fraction.down; }else{ //真分数 cout<<fraction.up<<"/"<<fraction.down; } if(fraction.up < 0){ cout<<")"; } } void add(Fraction a, Fraction b){ Fraction result; show(a); cout<<" + "; show(b); cout<<" = "; result.up = a.up * b.down + a.down * b.up; result.down = a.down * b.down; show(reduction(result)); } void substract(Fraction a, Fraction b){ Fraction result; show(a); cout<<" - "; show(b); cout<<" = "; result.up = a.up * b.down - b.up * a.down; result.down = a.down * b.down; show(reduction(result)); } void multiply(Fraction a, Fraction b){ Fraction result; show(a); cout<<" * "; show(b); cout<<" = "; result.up = a.up * b.up; result.down = a.down * b.down; show(reduction(result)); } void divide(Fraction a, Fraction b){ Fraction result; show(a); cout<<" / "; show(b); cout<<" = "; result.up = a.up * b.down; result.down = a.down * b.up; if(result.down == 0){ cout<<"Inf"; return; } show(reduction(result)); } int main(){ char s1[30],s2[30]; long long a1,b1,a2,b2; cin>>s1; cin>>s2; sscanf(s1, "%lld/%lld", &a1, &b1); sscanf(s2, "%lld/%lld", &a2, &b2); Fraction f1 = Fraction(a1,b1); Fraction f2 = Fraction(a2,b2); add(f1, f2); cout<<endl; substract(f1, f2); cout<<endl; multiply(f1, f2); cout<<endl; divide(f1, f2); return 0; }
标签:有理数,Fraction,四则运算,up,long,down,fraction,1034 From: https://www.cnblogs.com/yccy/p/16849924.html