【发布时间】:2019-07-13 02:06:50
【问题描述】:
我有以下代码,其中 if 条件似乎没有按预期工作。
例如,如果我输入 0.29,给出的结果是
季度:1 硬币:0 镍:4205264 便士:4
正如您所见,这是不正确的,因为在执行第一个 if 语句后,'if (cents >= 25)' 这将留下 4 的余数,它存储在 'cents' 变量中。这应该意味着接下来的两个“IF”语句返回一个“0”,最后一个 if 语句执行“if (cents >= 1)”。然而,情况并非如此,因为您可以看到 Nickles 返回的值是 4205264。
当你输入 1.17 时结果按预期返回:
季度:4 硬币:1 镍:1 便士:2
#include <cs50.h>
#include <math.h>
#include <stdio.h>
int main(void)
{
float dollars;
int cents;
int quartersUsed;
int dimesUsed;
int nickelsUsed;
int penniesUsed;
do
{
dollars = get_float("Float: ");
while (dollars <= 0) {
dollars = get_float("Float: ");
}
cents = roundf(dollars * 100);
printf("%i\n", cents);
if (cents >= 25) {
quartersUsed= cents / 25;
cents = cents % 25;
}
if (cents >= 10) {
dimesUsed = cents / 10;
cents = cents % 10;
}
if (cents >= 5) {
nickelsUsed = cents / 5;
cents = cents % 5;
}
if (cents >= 1) {
penniesUsed = cents / 1;
cents = cents % 1;
}
printf("Quarters: %i\n",quartersUsed);
printf("Dimes: %i\n",dimesUsed);
printf("Nickels: %i\n",nickelsUsed);
printf("Pennies: %i\n",penniesUsed);
}
while (dollars == false);
}
【问题讨论】:
-
这样的作业要教什么并不是很明显。一个好的结果是发现你根本不需要 if 语句。现在变量总是被赋值并且错误消失了。接下来修复美元 == false。