c++ - 如何在 cout 语句后打印 void 函数?

标签 c++ function fractions

我试图在我的值发送到函数后打印函数的输出。 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;   
}

最佳答案

使用reference来反射(reflect)topbottom的变化 并在调用 reduce_fraction

后在 add_fraction 函数中打印这些内容
void reduce_fraction ( int & top, int & bottom)
{                         ~~~        ~~~
 //...
}

然后,

reduce_fraction(top, bottom);
cout << top << "/" << bottom << endl; 

关于c++ - 如何在 cout 语句后打印 void 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28290113/

相关文章:

c++ - 使用 SDL_Flip 的 SDL 视频叠加层闪烁

python - 在当前类中循环调用另一个类函数

python - 如何在 Python 中使用 x DP 将分数写为十进制?

c++ - GLSL 构建错误

C++ DllMain API 调用

r - 通过数据帧在 R 中自动执行多项计算

delphi - 如何计算函数的运行时间?

c++ - 调用不带对象参数的非静态成员函数

python - 如何将 3/4 这样的分数作为输入?

c++ - 从 fstream 输入整数到 2d vector< vector<int>> C++