CS50 Pset1 Cash 示例 0.01 和 0.15 的错误输出
CS50 Pset1 Cash Example Wrong Output for 0.01 and 0.15
CS50 PSET1 现金示例
尝试为输入 0.01 和 0.15 获得正确的结果,但输出结果为“0”而不是 1 和 2。
代码:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int cents,coins;
do
{
float dollars = get_float("Change owed:");
cents = roundf(dollars*100);
}
while(cents < 0);
while (cents/25 != 0)
{
coins = cents/25;
cents= cents%25;
coins = coins + cents/10;
cents = cents%10;
coins = coins + cents/5;
cents = cents%5;
coins = coins + cents/1;
cents = cents%1;
}
printf("%i\n",coins);
}
输出:
:) cash.c 存在
:) cash.c 编译
:) 0.41 的输入产生 4
的输出
:( 输入 0.01 产生输出 1
应为“1\n”,而不是“32767\n”
:( 0.15 的输入产生 2
的输出
应为“2\n”,而不是“32767\n”
:) 1.6 的输入产生 7
的输出
:) 23 的输入产生 92
的输出
:) 4.2 的输入产生 18
的输出
:) 拒绝像 -1
这样的负输入
:) 拒绝非数字输入“foo”
:) 拒绝非数字输入“”
由于 while
语句,当输入小于 25 美分时,不会进行 coins
的计算。 由于使用了未初始化的非静态局部变量的(不确定)值,在这种情况下调用了未定义的行为。
cents
会变成零,循环无意义,所以你应该去除无意义和有害的循环。
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int cents,coins;
do
{
float dollars = get_float("Change owed:");
cents = roundf(dollars*100);
}
while(cents < 0);
/* remove this loop */
#if 0
while (cents/25 != 0)
{
#endif
coins = cents/25;
cents= cents%25;
coins = coins + cents/10;
cents = cents%10;
coins = coins + cents/5;
cents = cents%5;
coins = coins + cents/1;
cents = cents%1;
/* remove this loop */
#if 0
}
#endif
printf("%i\n",coins);
}
CS50 PSET1 现金示例
尝试为输入 0.01 和 0.15 获得正确的结果,但输出结果为“0”而不是 1 和 2。
代码:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int cents,coins;
do
{
float dollars = get_float("Change owed:");
cents = roundf(dollars*100);
}
while(cents < 0);
while (cents/25 != 0)
{
coins = cents/25;
cents= cents%25;
coins = coins + cents/10;
cents = cents%10;
coins = coins + cents/5;
cents = cents%5;
coins = coins + cents/1;
cents = cents%1;
}
printf("%i\n",coins);
}
输出:
:) cash.c 存在
:) cash.c 编译
:) 0.41 的输入产生 4
的输出
:( 输入 0.01 产生输出 1
应为“1\n”,而不是“32767\n”
:( 0.15 的输入产生 2
的输出
应为“2\n”,而不是“32767\n”
:) 1.6 的输入产生 7
的输出
:) 23 的输入产生 92
的输出
:) 4.2 的输入产生 18
的输出
:) 拒绝像 -1
这样的负输入
:) 拒绝非数字输入“foo”
:) 拒绝非数字输入“”
由于 while
语句,当输入小于 25 美分时,不会进行 coins
的计算。 由于使用了未初始化的非静态局部变量的(不确定)值,在这种情况下调用了未定义的行为。
cents
会变成零,循环无意义,所以你应该去除无意义和有害的循环。
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int cents,coins;
do
{
float dollars = get_float("Change owed:");
cents = roundf(dollars*100);
}
while(cents < 0);
/* remove this loop */
#if 0
while (cents/25 != 0)
{
#endif
coins = cents/25;
cents= cents%25;
coins = coins + cents/10;
cents = cents%10;
coins = coins + cents/5;
cents = cents%5;
coins = coins + cents/1;
cents = cents%1;
/* remove this loop */
#if 0
}
#endif
printf("%i\n",coins);
}