我对使用 C++ 进行编程还很陌生,我想了解我在这段代码中遗漏了算法流程的地方。该代码应该计算一组门票的费用(25 美元、30 美元、15 美元)。当我运行代码时,它会添加购买的门票总数,而不是所有门票的总费用。我相信我已经正确分配了变量,但我不知道为什么它没有将总成本加在一起,除非我需要单独分配这些变量。
任何帮助将不胜感激,谢谢!
using namespace std;
int main()
{
//declare variables
double orchestra = 25;
double mainFloor = 30;
double balcony = 15;
double totalSales = 0.0;
//enter input items
cout << "Enter orchestra tickets ";
cin >> orchestra;
cout << "Enter main floor tickets ";
cin >> mainFloor;
cout << "Enter balcony tickets ";
cin >> balcony;
//add the input items and print the total
totalSales = orchestra + mainFloor + balcony;
//display the total sales
cout << "Total Sales $" << totalSales << endl;
system("pause");
return 0;
} //end of main function
最佳答案
正如另一条评论中指出的那样,没有任何解释。
您将成本分配给用于输入门票数量的同一个变量(并因此覆盖成本)。相反,将成本放在单独的变量中(如果您愿意,也可以是常量),然后在获得用户输入后进行计算。
试试这个:
using namespace std;
int main()
{
//declare variables
double cost_per_orchestra = 25;
double cost_per_mainFloor = 30;
double cost_per_balcony = 15;
double orchestra = 0;
double mainFloor = 0;
double balcony = 0;
double totalSales = 0.0;
//enter input items
cout << "Enter orchestra tickets ";
cin >> orchestra;
cout << "Enter main floor tickets ";
cin >> mainFloor;
cout << "Enter balcony tickets ";
cin >> balcony;
//add the input items and print the total
totalSales = cost_per_orchestra * orchestra + cost_per_mainFloor * mainFloor + cost_per_balcony * balcony;
//display the total sales
cout << "Total Sales $" << totalSales << endl;
system("pause");
return 0;
} //end of main function
关于c++ - 如何在 C++ 中添加一组整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34847688/