我正在尝试在将值发送到函数后打印函数的输出。 cout语句需要一个字符串,但我不确定如何在保持数学正确的同时从reduce_fraction函数返回一个字符串。在我的add_fraction函数中,你会看到我只想打印添加的分数,然后是它下面的减少的分数。编译器不返回任何错误,但输出只显示“错误分数”答案。
#include <iostream>
#include <string>
using namespace std;
void reduce_fraction (int top, int bottom)
{
for (int i = top * bottom; i > 1; i--) {
if ((top % i == 0) && (bottom % i == 0)) {
bottom /= i;
top /= i;
}
}
}
void add_fraction (int numerator, int numerator2, int denominator, int
denominator2)
{
int top;
int bottom;
top = numerator2 * denominator + denominator2 * numerator;
bottom = denominator2 * denominator;
cout << "Improper Fraction -> ";
cout << top << "/" << bottom << endl;
cout << "Simplified Fraction -> ";
reduce_fraction(top, bottom);
}
int main()
{
int numerator;
int denominator;
int numerator2;
int denominator2;
char operation;
cout << "Input the numerator: ";
cin >> numerator;
cout << "Input the denominator: ";
cin >> denominator;
cout << "Input the numerator2: ";
cin >> numerator2;
cout << "Input the denominator: ";
cin >> denominator2;
cout << "Input the operation: ";
cin >> operation;
if (operation == '+'){
add_fraction(numerator, numerator2, denominator, denominator2);
}
return 0;
}
答案 0 :(得分:1)
使用参考反映top
和bottom
中的更改
并在致电add_fraction
reduce_fraction
函数中打印这些内容
void reduce_fraction ( int & top, int & bottom)
{ ~~~ ~~~
//...
}
然后,
reduce_fraction(top, bottom);
cout << top << "/" << bottom << endl;