[英]How to print void function after cout statement?
我將值發送到函數后嘗試打印函數的輸出。 cout語句需要一個字符串,但是我不確定如何在保持數學正確的同時從我的reduce_fraction函數返回一個字符串。 在我的add_fraction函數中,您將看到我只想打印添加的分數,然后打印縮小的分數。 編譯器不返回錯誤,但輸出僅顯示“ Improper 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;
}
使用引用反映top
和bottom
的更改,並在調用reduce_fraction
之后在add_fraction
函數中打印這些reduce_fraction
void reduce_fraction ( int & top, int & bottom)
{ ~~~ ~~~
//...
}
然后,
reduce_fraction(top, bottom);
cout << top << "/" << bottom << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.