C4700未初始化的变量,假设得到它的值使用cin

问题描述:

使用小费计算器程序的几个变量时遇到问题。一些变量使用cin获取它们的值,而不是在代码本身中声明。如果我尝试输入默认值,程序甚至不会查看输入值。因此,如果我将每个设置为0,最后计算的总金额为0.

Having trouble with a few variables for a tip calculator program. Some of the variables get their value using cin rather than being declared in the code itself. If I try to put in default values the program won't even look at the input values. So like if I set each to 0, the total amount calculated at the end would be 0.

int main()


int numberofDollars;
int numberofQuarters;
int numberofDimes;
int numberofNickles;
int numberofPennies;

string name;
const float dollar = 1.00;
const float quarter = 0.25;
const float dime = 0.10;
const float nickle = 0.05;
const float penny = 0.01;

float valueofDollars = numberofDollars * dollar;
float valueofQuarters = numberofQuarters * quarter;
float valueofDimes = numberofDimes * dime;
float valueofNickles = numberofNickles * nickle;
float valueofPennies = numberofPennies * penny;

double totalDeposit = valueofDollars + valueofQuarters + valueofDimes + valueofNickles + valueofPennies;

cout << "Enter account owner's name: ";
getline(cin, name);
cout << "Enter number of Dollars: ";
cin >> numberofDollars;
cout << "Enter number of Quarters: ";
cin >> numberofQuarters;
cout << "Enter number of Dimes: ";
cin >> numberofDimes;
cout << "Enter number of Nickles: ";
cin >> numberofNickles;
cout << "Enter number of Pennies: ";
cin >> numberofPennies;

cout << "Account Name: " << name << endl;
cout << "Total Deposit = $" << totalDeposit << endl;






system("pause");
return 0;


您不能将变量声明为像您所做的一样的计算。您必须计算之后的值您已将值放入变量。

You are using the variables before they are read. You can't declare a variable to be some calculation like you have done. You have to calculate the values after you have put values into the variables.

当你说

float valueofDollars = numberofDollars * dollar;

这意味着计算此刻的变量值的乘法存储它。这不意味着每当变量改变时计算。所以在读取变量后移动所有这些。

it means "calculate the multiplication of the variable values at this moment and store it." It doesn't mean "calculate this every time the variables change." So move all these after the variables have been read.