分数加减法

xiaoxiao2021-02-27  140

分数加减法

时间限制: 3000 ms  |  内存限制: 65535 KB 难度: 2 描述 编写一个C程序,实现两个分数的加减法 输入 输入包含多行数据  每行数据是一个字符串,格式是"a/boc/d"。  其中a, b, c, d是一个0-9的整数。o是运算符"+"或者"-"。  数据以EOF结束  输入数据保证合法 输出 对于输入数据的每一行输出两个分数的运算结果。  注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数 样例输入 1/8+3/8 1/4-1/2 1/3-1/3 样例输出 1/2 -1/4 0 题目分析:简单的根据分数的加减法规则进行计算即可。需要注意的有两点:①输出时候要考虑到特殊的情况。②求出的分数需要为最简式。 代码: #include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <vector> #include <queue> #include <stack> #include <map> #include <string> #include <algorithm> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int gcd(int top,int bottom){ //求 top 和 bottom的最大公约数 根据程序的执行逻辑和题意可知 第一次进入时top和bottom不为0 if(top == 0 && bottom == 0) { //都为0则不存在最大公约数 return -1; }else if(bottom == 0){ return top; }else return gcd(bottom,top%bottom); } struct Fraction{ int top; //分子 int bottom; //分母 Fraction operator+(const Fraction &x)const{ Fraction ans; ans.top=top*x.bottom+bottom*x.top; ans.bottom=bottom*x.bottom; return ans; } Fraction operator -(const Fraction &x)const{ Fraction ans; ans.top=top*x.bottom-bottom*x.top; ans.bottom=bottom*x.bottom; return ans; } void reduction() { //化简函数 if(top == 0){ return; } //cout<<top<<endl; int gcdnum=gcd(top,bottom); //求分子和分母的最大公约数 //cout<<gcdnum<<endl; //分子分母同时除以最大公约数即得到最简式 top=top/gcdnum; bottom=bottom/gcdnum; } void output(){ //输出的特殊情况 :top=0 bottom=1,-1 bottom<0 if(top == 0 || bottom == 0){ //题意说bottom不为0 cout<<"0"<<endl; return; } int tmp = top*bottom; //由题意可知bottom不会为负 if(tmp > 0) { if(abs(bottom) == 1){ cout<<abs(top)<<endl; return; }else{ cout<<abs(top)<<"/"<<abs(bottom)<<endl; return; } }else{ if(abs(bottom) == 1){ cout<<"-"<<abs(top)<<endl; return; }else{ cout<<"-"<<abs(top)<<"/"<<abs(bottom)<<endl; return; } } } }; int main(int argc, char** argv) { char input[7]; while(scanf("%s",input)!=EOF){ Fraction ans; Fraction a,b; a.top=input[0]-'0'; a.bottom=input[2]-'0'; char op=input[3]; b.top=input[4]-'0'; b.bottom=input[6]-'0'; if(op == '+'){ ans=a+b; }else{ ans=a-b; } ans.reduction(); ans.output(); } return 0; }代码分析: 本题通过求出分子分母的最大公约数来进行化简分式。 收获:感觉没啥收获。 附上所谓的优秀代码: #include<stdio.h> 02. char str[20]; 03. int Gcd(int m,int n) 04. { 05. if (m==0) return n; 06. return Gcd(n%m,m); 07. } 08. int main() 09. { 10. int fz,fm,gcd; 11. while(scanf("%s",str)!=EOF) 12. { 13. if(str[3]=='-') 14. fz=(str[0]-'0')*(str[6]-'0')-(str[2]-'0')*(str[4]-'0'); 15. else fz=(str[0]-'0')*(str[6]-'0')+(str[2]-'0')*(str[4]-'0'); 16. if(fz) 17. { 18. fm=(str[2]-'0')*(str[6]-'0'); 19. gcd=Gcd(fz,fm); 20. if(gcd<0) gcd=-gcd; 21. if(fm/gcd==1) printf("%d\n",fz/gcd); 22. else printf("%d/%d\n",fz/gcd,fm/gcd); 23. } 24. else puts("0"); 25. } 26. } 对比: 我的代码基本上用的是面向对象的思想,显得比较冗长。下面的代码则是直接以面向过程的方式处理,简洁一些。 另外一点是我的代码中考虑了就本题而言不会发生的情况,比如gcd函数中同时等于0对于本题而言不会发生,但抛去本题而言求两个数的最大公约数 是需要考虑的。
转载请注明原文地址: https://www.6miu.com/read-12230.html

最新回复(0)