我是 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;
}
本课的重点是在代码中使用函数和传递参数。我不应该使用全局变量。如果您有更好的方法来做到这一点,请分享。
原文由 hcas 发布,翻译遵循 CC BY-SA 4.0 许可协议
减少到三行(其他错误类似):
虽然定义了
wall
,但没有定义gallons
。你想从哪里得到gallons
?结果隐藏在另一个函数的深处。你想怎么把它从那里弄出来?好吧,你需要一个返回值:
这样,您可以像这样使用您的函数:
类似地用于其他函数和变量。
通常,在同一个函数中混合逻辑(计算)和输出 并不是 一个好主意。所以我宁愿将写入控制台移动到
main
函数:注意?现在所有输入/输出都处于同一水平……
旁注:如果在定义之前不使用函数,则无需在定义函数之前声明它们:
反例:
如果您仍然想保留声明,那是一个风格问题(但在管理不同编译单元中的代码时会变得很重要,因为您将在头文件中拥有声明——您将在下一课中很快遇到)。