无法弄清楚如何在while循环C中正确增加变量 [英] Cannot figure out how to properly increment a variable inside of a while loop, C
问题描述
在我的IDE中重新编写代码后,今天是第八次,我的菜鸟犯了个错误,即为我的输入提供了一个错误的数据类型,该类型已得到修复,但我的输出仍然不正确.
After re-writing my code in my IDE, for the 8th time today, I have made rookie mistake of giving my inputs a false data type, that has been fixed but my outputs still are incorrect.
关于我的目标的详细信息:进行更改时,您希望最大程度地减少为每个客户分配的硬币数量.好吧,假设出纳员欠客户一些零钱,并且出纳员的抽屉中有25美分,10美分,5美分和1美分的便士.要解决的问题是确定要交付给客户的硬币以及每种硬币的数量.
Details about my goal: When making change, odds are you want to minimize the number of coins you’re dispensing for each customer. Well, suppose that a cashier owes a customer some change and in that cashier’s drawer are quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢). The problem to be solved is to decide which coins and how many of each to hand to the customer.
预期结果:
欠款:0.41
4
实际结果:
欠款:0.41
3
Expected Result:
Change owed: 0.41
4
Actual result:
Change owed: 0.41
3
#include <math.h>
#include <cs50.h>
#include <stdio.h>
int main (void)
{
float dollars;
int changeowed = 0;
do
{
dollars = get_float ("Change owed: ");
}
while (dollars < 0);
float cents = round(dollars * 100);
while (cents >= 25)
{
cents = cents - 25;
changeowed++;
}
while (cents > 10)
{
cents = cents - 10;
changeowed++;
}
while (cents > 5)
{
cents = cents - 5;
changeowed++;
}
while (cents > 1)
{
cents = cents - 1;
changeowed++;
}
printf("%i \n", changeowed);
}
推荐答案
问题出在这里:有4个循环,一个循环四分之一,一个角钱,一个镍币,一个便士.第一个循环条件正确:
Here's the problem: There are 4 loops, one for quarters, one for dimes, one for nickels, and one for pennies. The first loop condition is correct:
while (cents >= 25)
其他三个不正确:
while (cents > 10)
while (cents > 5)
while (cents > 1)
这些都需要更改为使用> =
代替>
.
These all need to be changed to use >=
in place of >
.
这篇关于无法弄清楚如何在while循环C中正确增加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!