为什么我的代码无法打印int
coins
?
运行调试系统时没有看到任何错误。
#include <cs50.h>
#include <stdio.h>
int main(void)
{ // getting the user validation
printf("please enter a amount of change \n");
int change = get_int();
int coins = 0;
if (change > 0 && change <= 0 && change != 0)
printf("Change: %i\n", change);
if (change > 0)
{
printf("Change: %i\n", change);
}
if (change < 0 )
{
printf("please enter a positve number \n");
}
if (change == 0)
{
printf("Coins: 0 \n");
}
//were it counts the amount of coins
float changef = (int)change;
float qaurter = 0.25;
float dime = 0.10;
float nickel = 0.05;
float penny = 0.01;
while (changef / qaurter)
{
coins++;
return changef - qaurter;
}
while (changef / dime)
{
coins++;
return changef - dime;
}
while (changef / nickel)
{
coins++;
return changef - nickel;
}
while (changef / penny)
{
coins++;
return changef - penny;
}
printf("Coins: %i\n",coins);
}
答案 0 :(得分:3)
您的循环中包含return
个语句:
while (changef / qaurter)
{
coins++;
return changef - qaurter;
}
从main()
返回相当于退出该计划。您需要修改代码以避免在循环中使用return
。例如(包括拼写修正):
while (changef / quarter)
{
coins++;
changef -= quarter;
}
虽然坦率地说,你可以完全避免循环:
int extra = changef / quarter;
coins += extra;
changef -= extra * quarter;
然而,在可行之前还需要做更多的手术,因为你只对整数美元进行了更改,但你的quarter
和朋友定义为float
变量的小数值。您需要仅以美分(int quarter = 25;
)工作,或者允许用户首先输入浮点值,或者......