这是我的计划。它应该采用2个分数并在建模结构时将它们加在一起。我遇到了一些麻烦。我收到一些错误消息。复制此代码,看看您是否可以正确调试它并解释您的操作。我很困难!非常感谢你!
#include <cstdlib>
#include <iostream>
#include <math.h>
/*
Name: Fraction
Author: Grant Birkinbine
Date: 13/10/14 17:33
Description: Takes two fractions and outputs them in different ways
*/
using namespace std;
//Struct
struct fraction{
int numer, denom ;
};
//Function to print fractions
void displayfractionadd (fraction a) {
cout << "Addition: " << add.numer << "/" << add.denom << endl;
}
//Function to get fraction info
fraction newfraction() {
fraction a1;
cout << "Enter numerator: " ;
cin >> a1.numer ;
cout << "Enter denomerator: " ;
cin >> a1.denom ;
return a1;
}
//Function to add fractions
fraction addition(fraction a1, fraction a2) {
fraction add;
add.denom = (a1.denom * a2.denom) ;
add.numer = a1.numer * a2.denom + a1.denom * a2.numer;
return add;
}
//Main
int main(int argc, char *argv[])
{
cout << "Fraction 1 = " ;
cout << endl;
fraction fraction1 = newfraction();
fraction fraction2 = newfraction();
cout << endl;
cout << "Solutions: " ;
fraction newadd = addition(fraction a1, fraction a2) ;
cout << endl;
displayfractionadd (fraction a);
system("PAUSE");
return EXIT_SUCCESS;
}
答案 0 :(得分:1)
这些行不会调用函数:
fraction newadd = addition(fraction a1, fraction a2) ;
//...
displayfractionadd (fraction a);
这些行声明了函数,而不是调用它们。要调用函数,只需提供参数:
fraction newadd = addition(a1, a2);
//...
displayfractionadd (a);
其次,a
,a1
和a2
未在任何地方声明。您的意思是fraction1
fraction2
和newadd
吗?
fraction newadd = addition(fraction1, fraction2);
//...
displayfractionadd (newadd);
最后,除非您有特定原因,否则请fraction
或reference
传递const reference
,而不是按值传递。例如:
fraction addition(const fraction& a1, const fraction& a2)
{
//... body of function here
}
由于a1和a2都未在addition
函数中更改,因此参数应为const引用,以指示(并强制执行)a1和a2不会更改。此外,通过引用传递不会调用无关的副本。