本文主要是介绍简单数学问题之分数的表示与化简,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
分数的化简
#include <iostream>
#include <cmath>//调用abs函数
using namespace std;
int divide(int a,int b){if(b==0) return a;else return divide(b,a%b);
}
struct fraction{int up;//分子int down;//分母
}result;
fraction reduction(fraction result){if(result.down<0){//1.分母为负数,只需令分子为负数即可result.up=-result.up;//分子变为负数result.down=-result.down;//分母变为正数}if(result.up==0) //2.分子为0,只需令分母为1即可result.down=1;else {int num=divide(abs(result.up),abs(result.down));//求公约数result.up/=num;//化简即约去公约数result.down/=num;}return result;
}
int main(){cin>>result.up>>result.down;result=reduction(result);cout<<result.up<<","<<result.down<<endl;return 0;
}
分数的加法
#include <iostream>
#include <cmath>//调用abs函数
using namespace std;
int divide(int a,int b){if(b==0) return a;else return divide(b,a%b);
}
struct fraction{int up;//分子int down;//分母
}result;
fraction reduction(fraction result){if(result.down<0){//1.分母为负数,只需令分子为负数即可result.up=-result.up;//分子变为负数result.down=-result.down;//分母变为正数}if(result.up==0) //2.分子为0,只需令分母为1即可result.down=1;else {int num=divide(abs(result.up),abs(result.down));//求公约数result.up/=num;//化简即约去公约数result.down/=num;}return result;
}
fraction add(fraction f1,fraction f2){fraction result;//通分再相加result.up=f1.up*f2.down+f2.up*f1.down;//分子result.down=f1.down*f2.down;//分母return reduction(result);
}
int main(){fraction f1,f2;cin>>f1.up>>f1.down;cin>>f2.up>>f2.down;result=add(f1,f2);cout<<result.up<<","<<result.down<<endl;return 0;
}
分数的乘法
#include <iostream>
#include <cmath>//调用abs函数
using namespace std;
int divide(int a,int b){if(b==0) return a;else return divide(b,a%b);
}
struct fraction{int up;//分子int down;//分母
}result;
fraction reduction(fraction f){if(f.down<0){f.up=-f.up;f.down=-f.down;}if(f.up==0)f.down=1;else {int num=divide(abs(f.up),abs(f.down));f.up/=num;f.down/=num;}return f;
}
fraction multiply(fraction f1,fraction f2){fraction result;result.up=f1.up*f2.up;result.down=f1.down*f2.down;return reduction(result);
}
int main(){fraction f1,f2;cin>>f1.up>>f1.down;cin>>f2.up>>f2.down;result=multiply(f1,f2);cout<<result.up<<","<<result.down<<endl;return 0;
}
这篇关于简单数学问题之分数的表示与化简的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!