针对小费计算器程序的一些变量有问题。一些变量使用cin获取其值,而不是在代码本身中声明。如果我尝试输入默认值,程序甚至不会查看输入值。因此,如果我将每个设置为0,则结束时计算的总量将为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;
答案 0 :(得分:4)
您在阅读之前使用变量。你不能声明变量就像你做的那样进行一些计算。您必须在中将值放入变量之后计算值。
当你说
时float valueofDollars = numberofDollars * dollar;
这意味着“此时计算变量值的乘法并存储它。”它并不意味着“每次变量都会计算出来”。因此,在读取变量后移动所有这些。
答案 1 :(得分:0)
您首先计算未初始化值的值,然后读取硬币数量和,在阅读后不再使用它们。
答案 2 :(得分:0)
我想这就是你想做的事情:
#include <iostream>
using namespace std;
int main() {
double numberofDollars, numberofQuarters,
numberofDimes, numberofNickles,
numberofPennies;
string name;
const double quarter = 0.25, dime = 0.10,
nickle = 0.05, penny = 0.01;
double valueofDollars, valueofQuarters, valueofDimes,
valueofNickles, valueofPennies, totalDeposit;
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;
valueofDollars = numberofDollars;
valueofQuarters = numberofQuarters * quarter;
valueofDimes = numberofDimes * dime;
valueofNickles = numberofNickles * nickle;
valueofPennies = numberofPennies * penny;
totalDeposit = valueofDollars + valueofQuarters + valueofDimes + valueofNickles + valueofPennies;
cout << "Account Name: " << name << endl;
cout << "Total Deposit = $" << totalDeposit << endl;
return 0;
}