c++ - 如何在 C++ 中添加一组整数

标签 c++

我对使用 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/

相关文章:

c++ - C/C++ 代码的结果

c++ - C 或 C++ 中乘法和除法的较高部分?

c++ - 使用带有 set_intersection 的 map

c++ - 将 Keras 模型转换为 C++

c# - import c++ unmanaged dll to c#问题

c++ - 是否可以使用不在 header 中的 C++ 库代码?

c# - 枚举Windows中特定类型的文件

c++ - OpenCV 从尺寸中找到文本比例

c++ - 在 C++ 中分配大小为 10000 10000 3 的 3 维 vector

c++ - 多重继承 C++,转换是如何工作的?