gpt4 book ai didi

c++ - 在 C++ 中乘法变量有问题。 (除非硬编码,否则 C++ 不想将它们相乘)

转载 作者:行者123 更新时间:2023-11-28 02:43:11 25 4
gpt4 key购买 nike

我最近选择了 cpp,并一直在做几个非常小的项目来熟悉这门语言,但我遇到了一个无论在网上哪里都无法弄清楚的困境。

#include <iostream>
using namespace std;

int main(){
double salesTax = 0.875, gross = 0, tax = (gross*salesTax), total = (salesTax + gross); //Variables

cout << "Welome to StoreMart!" << endl;

cout << "How much is your total? "; //asks user for an amount of money spent (not including tax).
cin >> gross; //saves total spent in the gross variable

cout << "\n\nThat brings your total with tax to $" << total << "." << endl; //prints the users total with tax.

cout << "Price: " << gross << "$ \n\nSales Tax: $" << tax << " @" <<
salesTax << "% \n\nTotal: $" << total << endl; //prints out something similar to the receipts you get at Wal-Mart.

return 0;
}

如您所知,我正在构建一个小型收银机类型的程序,但问题是无论何时运行,我都只会得到如下所示的输出。

http://imgur.com/7ndthUX (无法上传图片直到 10 分所以希望 imgur 没问题:))

如有任何帮助,我们将不胜感激(如果我的数学有问题,请不要介意我对让我的程序正确运行比让数学变得完美更感兴趣。)

最佳答案

您正在根据初始值 0 计算所有依赖于 gross 的值。获取 gross 输入,然后然后计算税金和总计,在输出之前。

其他一些修复:

  • 8.75% 的销售税为 0.0875
  • 您只添加了销售税百分比,而不是计算值
  • 您想将最终总计显示到小数点后两位

我在下面添加了修复。

#include <iostream>
using namespace std;

int main(){
double salesTax = 0.0875;
double gross = 0;
double tax = 0;
double total = 0; //Variables with initial values

cout << "Welome to StoreMart!" << endl;

cout << "How much is your total? "; //asks user for an amount of money spent (not including tax).
cin >> gross; //saves total spent in the gross variable
tax = (gross*salesTax); //calculate tax
total = (tax + gross); //calculate total

cout.precision(2);
cout << "\n\nThat brings your total with tax to $" << total << "." << endl; //prints the users total with tax.

cout << "Price: " << gross << "$ \n\nSales Tax: $" << tax << " @" <<
salesTax*100 << "% \n\nTotal: $" << fixed << total << endl; //prints out something similar to the receipts you get at Wal-Mart.

return 0;

关于c++ - 在 C++ 中乘法变量有问题。 (除非硬编码,否则 C++ 不想将它们相乘),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25256688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com