繁体   English   中英

我的代码每次运行时都会输出一个随机数

[英]my codes outputs a random number every time I run it

我的代码的目的是告诉用户不同价值所需的最小硬币数量(四分之一、一角硬币、镍币、便士)是多少,价值来自用户。 我的代码首先询问用户他们想要解决的现金(美元),然后我的程序将现金(美元)转换为 *100 美分,之后我的程序是一个循环,减去最大的硬币,同时每次加 1我设置了计数器,但是当我运行所有这些时,我没有收到任何错误,但是我没有得到我想要的输出,我注意到它采用了用户值并在末尾添加了 5。 (复制和粘贴时间距混乱)

#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
//get the amount of change and make sure it is more than 0
float dollar;
do
{
    dollar = get_float("Enter change owed in dollars: ");
}
while (dollar < 0.001);

// make the dollar value into cents
int cent = round(dollar * 100);

// make a loop so that I can subtract the largest coin possible
int i = 0;

while(cent <= 25)
{
    (cent = cent - 25);
    i++;
}

while(cent <= 10 || cent > 25)
{
    (cent = cent -10);
    i++;
}

while(cent <= 5 || cent >10)
{
    (cent = cent - 5);
    i++;
}

while(cent <= 1 || cent > 5)
{
    (cent = cent - 1);
    i++;
}
//print out how many coins were used
printf("The minimum coins to be returned in %i \n", i);

}

输出不是随机的,它是i在整个代码中递增的次数,这似乎是正确的,对于 5 的输入,500 美分的数量。

在大多数情况下,它将在此循环中递增:

while(cent <= 10 || cent > 25)
{
    (cent = cent -10);
    i++;
}

48 次。 然后剩下的在这个:

while(cent <= 5 || cent >10)
{
    (cent = cent - 5);
    i++;
}

7 次,所以代码按照您的要求执行,问题是,您的代码是否按照您的要求执行?

我会说,如果你想要给定数量的美元中最少的美分硬币,你会想要这样的东西:

while (cent >= 25) { // count the amount of 25 cent coins
    cent -= 25;
    i++;
}

while (cent >= 10) { // count the number of 10 cent coins for the remaining amount
    cent -= 10;
    i++;
}

while (cent >= 5) { // same
    cent -= 5;
    i++;
}

while (cent >= 1) { // same
    cent -= 1;
    i++;
}

现场演示

作为旁注和建议,学会很好地使用调试器,这是该行业非常有价值的技能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM