using namespace std;
int amount_total(int amount_paid, int& amountleft), quarters(int&
amountleft), dimes(int& amountleft), pennies(int& amountleft);
int amount_total(int amount_paid, int& amountleft)
{
const int TOTALVALUE = 99;
cout << "You have bought a candy bar that's 99 cents. \n"
<< "Please insert the amount paid. " << endl;
cin >> amount_paid;
amountleft = TOTALVALUE - amount_paid;
cout << "You have to pay : " << amountleft << " cents. \n" << endl;
return(0);
}
int quarters(int& amountleft)
{
const int QUARTERS = 25;
int total, count_Quarters;
count_Quarters = 0;
while (amountleft > 0 || amountleft >= QUARTERS)
{
total = amountleft - QUARTERS;
count_Quarters++;
}
return(count_Quarters);
}
int dimes(int& amountleft)
{
const int DIMES = 10, QUARTERS = 25;
int total, count_Dimes;
count_Dimes = 0;
while (amountleft > 0 || amountleft <= QUARTERS)
{
total = amountleft - DIMES;
count_Dimes++;
}
return(count_Dimes);
}
int pennies(int& amountleft)
{
const int PENNIES = 1, DIMES = 10;
int total, count_Pennies;
count_Pennies = 0;
while (amountleft >= 0 || amountleft <= DIMES)
{
total = amountleft - PENNIES;
count_Pennies++;
}
return(count_Pennies);
}
int main()
{
int amount_paid, amountleft, Count_Quarters,
Count_Dimes, Count_Pennies, total_amount;
total_amount = amount_total(amount_paid, amountleft);
Count_Quarters = quarters(amountleft);
Count_Dimes = dimes(amountleft);
Count_Pennies = pennies(amountleft);
cout << "You'll get : " << Count_Quarters << " quarters, " <<
Count_Dimes << " dimes, and " << Count_Pennies << " pennies. \n"
<< endl;
return 0;
}
//示例运行:
你买了一个99美分的糖果吧。 请输入已付金额。 36 你必须支付:63美分。我最初的计划是运行程序,主程序只运行函数,函数会返回变量,但它没有这样做而且它只运行第一个函数
答案 0 :(得分:-1)
正如评论中提到的rex所有的while循环都是无限的,所以永远不会停止循环。你的程序在你的第二个功能“宿舍”内实现冻结。看看那里的事情如何:当你离开你的函数amount_total时,它返回0并将它分配给一个“total_amount”变量,之后它已经为“amountleft”变量赋值等于“TOTALVALUE - amount_paid”。您将此值(在“amountleft”变量内)传递给第二个函数“quarters”。如果您的示例“amountlef”变量等于63,它大于“0”并且也大于QUARTERS(因为它是25)。所以你在这里开始循环并且循环的每次迭代你的变量“amountleft”保持具有相同的值,即63,因为它在你的while循环内没有改变,留下你必须改变“amountleft”的循环或者设置任何类型的休息。为了使它更加可见,可以在循环中设置“cout”,看看那里发生了什么。像这样。
21 int quarters( int& amountleft ) {
22 const int QUARTERS = 25;
23 int total, count_Quarters;
24 count_Quarters = 0;
25 cout << "before while-loop" << endl;
26 while( amountleft > 0 || amountleft >= QUARTERS ) {
27 cout << "count_Quarters = " << count_Quarters << endl;
28 cout << "amountleft = " << amountleft << endl;
29 total = amountleft - QUARTERS;
30
31 count_Quarters++;
32 }
33 cout << "after while-loop" << endl;
34 return count_Quarters;
35 }
请记住,由于您尚未定义“total”变量,因此它可以包含任何垃圾,但通常不会。无论如何,在使用它之前将任何值(例如0等)分配给变量可能是好的。