无法弄清楚如何在 while 循环内正确递增变量,C [英] Cannot figure out how to properly increment a variable inside of a while loop, C
问题描述
在我的 IDE 中重写我的代码后,今天第 8 次,我犯了菜鸟错误,给我的输入一个错误的数据类型,这个错误已经修复,但我的输出仍然不正确.
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
", 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屋!