我试图完成一项作业,但我一般都对数学表达式和变量有困难。我试图创建一个程序,用于获取杂货的用户信息,然后输出收据。这是我的代码。
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
程序输出0表示全部或负数。
答案 0 :(得分:2)
您的计算必须在您阅读之前阅读,而不是之前。您根据未初始化的变量进行计算。
答案 1 :(得分:2)
声明和初始化,如
double firstExt = firstPrice * firstCount;
将firstExt
初始化为firstPrice
和firstCount
的当前值的乘积。
它不会设置一些魔法,因此只要firstExt
或firstPrice
的值发生变化,就会重新计算firstCount
的值。
在您执行此操作时,firstPrice
和firstCount
是未初始化的变量。访问类型为int
的未初始化变量的值会给出未定义的行为。
你需要做的是像
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
如果此时不需要firstExt
的值,则可以在此处声明;
double firstExt = firstPrice*firstCount; // do the calculation here
这意味着任何早期使用firstExt
都会给编译器提供诊断。