为什么我的程序对某些测试正确运行,而对其他测试却不正确? [英] Why my program works correctly for some tests and not for others?
本文介绍了为什么我的程序对某些测试正确运行,而对其他测试却不正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我测试的结果:
:) greedy exists
:) greedy compiles
:( input of 0.41 yields output of 4
expected "4\n", not "3\n"
:( input of 0.01 yields output of 1
expected "1\n", not "0\n"
:) input of 0.15 yields output of 2
:) input of 1.6 yields output of 7
:) input of 23 yields output of 92
:) input of 4.2 yields output of 18
:) rejects a negative input like -.1
:) rejects a non-numeric input of "foo"
:) rejects a non-numeric input of ""
这是代码:
#include <stdio.h>
#include <cs50.h>
void count_coins();
int coin = 0;
float change = 0;
int main(void)
{
do
{
change = get_float("How much change is owed? ");
}
while (change < 0);
count_coins();
printf("%i\n", coin);
}
void count_coins()
{
while (change > 0.24)
{
coin++;
change -= 0.25;
// printf("%.2f\n", change);
}
while (change > 0.09)
{
coin++;
change -= 0.10;
// printf("%.2f\n", change);
}
while(change > 0.04)
{
coin++;
change -= 0.05;
// printf("%.2f\n", change);
}
while (change >= 0.01)
{
coin++;
change -= 0.01;
// printf("%.2f\n", change);
}
}
推荐答案
As Havenard已经写道,问题在于更改
被存储为 float
。
对于这样的程序,更改
必须存储为整数值。
As Havenard already wrote, the problem is that change
was stored as float
.
For such a programm change
must be stored as an integer value.
此代码与 int
而不是 float
:
#include <stdio.h>
#include <cs50.h>
void count_coins (void);
int coin = 0;
int change = 0;
int main (void) {
do {
change = 41; // insert a get integer function here
} while (change < 0);
count_coins();
printf("%i\n", coin);
}
void count_coins (void) {
while (change >= 25) {
coin++;
change -= 25;
}
while (change >= 10) {
coin++;
change -= 10;
}
while(change >= 5) {
coin++;
change -= 5;
}
while (change >= 1) {
coin++;
change -= 1;
}
}
这篇关于为什么我的程序对某些测试正确运行,而对其他测试却不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文