我需要一些货币计划的帮助

时间:2015-10-07 23:43:19

标签: c++

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{

	int quarters;
	int dimes = (quarters * 5);
	int pennies = (quarters * 25);
	int nickles = (pennies / 10);

	cout << "Please enter the amount of quarters you wish to convert" << endl;
	cin >> quarters;

	cout << "Pennies = " << pennies << endl;
	cout << "Dimes = " << dimes << endl;
	cout << "Nickles = " << nickles << endl;
	cin.get();
	cin.get();

	return 0;
}

出于某种原因,我一直收到一个C4700错误,说四分之一是一个未初始化的局部变量,但是如果季度是被解雇的,我该怎么办?我尝试输入int quarters = 0,但这搞砸了程序的计算。有任何想法吗?

4 个答案:

答案 0 :(得分:1)

错误信息清楚地说明了什么是错的。您已声明quarters但在使用之前尚未初始化。 把这个

cout << "Please enter the amount of quarters you wish to convert" << endl;
cin >> quarters;

int dimes = (quarters * 5);
int pennies = (quarters * 25);
int nickles = (pennies / 10); 

答案 1 :(得分:1)

初始化变量quarters,然后在计算中使用它。

int quarters;
cout<<"Please enter the amount of quarters you wish to convert" << endl;
cin>>quarters;

int dimes = (quarters * 5);
int pennies = (quarters * 25);
int nickles = (pennies / 10);

答案 2 :(得分:0)

试试这个:

int main()
{

    int quarters;
    int dimes;
    int pennies;
    int nickles;

    cout << "Please enter the amount of quarters you wish to convert" << endl;
    cin >> quarters;

    dimes = (quarters * 5);
    pennies = (quarters * 25);
    nickles = (pennies / 10);

    cout << "Pennies = " << pennies << endl;
    cout << "Dimes = " << dimes << endl;
    cout << "Nickles = " << nickles << endl;
    cin.get();
    cin.get();

    return 0;
}

答案 3 :(得分:0)

正如其他人所说,你必须在使用之前获得输入,例如:

int quarters;
cout << "Please enter the amount of quarters you wish to convert" << endl;
cin >> quarters;

然后,在此之后,您可以计算其他值:

int dimes = (quarters * 5);
int pennies = (quarters * 25);
int nickles = (pennies / 10);

那就是说,让我们看看它为什么会发生。也许你认为当你分配一个&#34;公式&#34;对于一个变量(如dimes = quarters * 5),该值将始终重新计算,与Excel的操作类似。 C ++并不是这样的:当你为一个变量赋值时,你没有定义一个将自动更新的通用公式,而是在那个时刻计算结果。和程序从顶部到底部运行。因此,当您到达定义dimespenniesnickles的行时,您将获取quarters的(尚未定义的)值并尝试使用它来计算其他变量。这里程序停止了,但如果它继续并且它到达cin的行,它确实会将值存储在quarters中,但其他3个变量不会被更新!