我是C ++的新手,我不明白为什么会收到此错误。在5个类似3标记错误的语句中,其他两个都可以。错误在主要功能上。
#include <iostream>
using namespace std;
// Function declaration
void getGallons(int wall);
void getHours(int gallons);
void getCostpaint(int gallons, int pricePaint);
void getLaborcharges(int hours);
void getTotalcost(int costPaint, int laborCharges);
// Function definition
void getGallons(int wall)
{
int gallons;
gallons = wall / 112;
cout << "Number of gallons of paint required: " << gallons << endl;
}
// Function definition
void getHours(int gallons)
{
int hours;
hours = gallons * 8;
cout << "Hours of labor required: " << hours << endl;
}
// Function definition
void getCostpaint(int gallons, int pricePaint)
{
int costPaint;
costPaint = gallons * pricePaint;
cout << "The cost of paint: " << costPaint << endl;
}
// Function definition
void getLaborcharges(int hours)
{
int laborCharges;
laborCharges = hours * 35;
cout << "The labor charge: " << laborCharges << endl;
}
// Funtion definition
void getTotalcost(int costPaint, int laborCharges)
{
int totalCost;
totalCost = costPaint + laborCharges;
cout << "The total cost of the job: " << totalCost << endl;
}
// The main method
int main()
{
int wall;
int pricePaint;
cout << "Enter square feet of wall: ";
cin >> wall;
cout << "Enter price of paint per gallon: ";
cin >> pricePaint;
getGallons(wall);
getHours(gallons); // error here
getCostpaint(gallons, pricePaint);
getLaborcharges(hours); // error here
getTotalcost(costPaint, laborCharges); //error here
return 0;
}
本课程侧重于在代码中使用函数和传递参数。我不应该使用全局变量。如果您有更好的方法,请分享。
减少到三行(其他错误类似):
int wall;
getGallons(wall);
getHours(gallons); // error here
虽然定义了wall
,但没有定义gallons
。而且您想从哪里获得gallons
?结果隐藏在另一个函数的深处。您想如何从那里得到它?
嗯,您需要一个返回值:
int getGallons(int wall)
//^^^ !
{
int gallons = wall / 112;
// ...
return gallons; // !
}
这样,您可以像这样使用您的函数:
int gallons = getGallons(wall);
// now gallons is defined and you can use it:
getHours(gallons);
类似地用于其他函数和变量。
通常,将逻辑(计算)和输出以相同的功能混合是一个好主意。因此,我宁愿将控制台编写工作转移到main
函数中:int getGallons(int wall) { return wall / 112; }
int getHours(int gallons) { return gallons * 8; }
int wall;
std::cin >> wall;
int gallons = getGallons(int wall);
std::cout << ...;
int hours = getHours(gallons);
std::cout << ...;
通知?现在所有输入/输出处于同一级别...
旁注:如果在定义之前不使用函数,则不必在定义函数之前先声明它们:
//void f(); // CAN be ommitted
void f() { };
void g() { f(); }
反例:
void f();
void g() { f(); } // now using f before it is defined, thus you NEED do declare it
void f() { };
如果您仍然希望保留声明只是样式问题(但是在不同编译单元中管理代码时,它将变得很重要,因为然后将声明保存在头文件中,您将在下一课中很快遇到) 。