【发布时间】:2017-08-16 00:15:39
【问题描述】:
我对 C 很陌生。我来自 python 背景。我想知道我的代码哪里出错了。
我正在做 cs50 贪心问题。我的代码有什么问题?它适用于某些数字,但其他数字不起作用。我试图从用户那里得到一个输入,询问要返还多少零钱,然后计算我可以仅使用 $.25、$.10、$.05、$.01 返还的最小硬币数量
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float n;
do
{
n = get_float("How much change is owed?\n");
}
while(n == EOF);
int minimumamountofcoins = 0;
if (n/.25 >=1){
do
{
n -= .25;
minimumamountofcoins++;
}
while (n/.25 >= 1);
}
if (n/.1 >=1){
do
{
n -= .1;
minimumamountofcoins++;
}
while (n/.1 >=1);
}
if(n/.05 >=1){
do
{
n -= .05;
minimumamountofcoins++;
}
while (n/.05 >=1);
}
if (n/.01 >=1){
do
{
n -= .01;
minimumamountofcoins++;
}
while (n/.01 >=1);
}
printf("The minimum amount of coins is %d\n", minimumamountofcoins);
}
新代码:(除了进入 4.2 时可以正常工作)
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float n;
do
{
n = get_float("How much change is owed?\n");
}
while(n == EOF);
int cents = (int)(n * 100);
int minimumamountofcoins = 0;
if (cents/25 >= 1){
while (cents/25 >= 1)
{
cents -= 25;
minimumamountofcoins++;
}
}
if (cents/10 >= 1){
while (cents/10 >= 1)
{
cents -= 10;
minimumamountofcoins++;
}
}
if(cents/5 >= 1){
while (cents/5 >= 1)
{
cents -= 5;
minimumamountofcoins++;
}
}
if (cents/1 >= 1){
while (cents/1 >= 1)
{
cents -= 1;
minimumamountofcoins++;
}
}
printf("The minimum amount of coins is %d\n", minimumamountofcoins);
}
【问题讨论】:
-
为什么不举一个您的代码不起作用的输入示例?对于该输入,请说出您期望的输出以及程序返回的内容。
-
请研究“改变”问题。建议使用整数和美分。 Is floating point math broken?
-
一些建议:使用整数(所有货币金额以便士为单位),您不需要最后的 .01 while 循环(剩余金额是便士数);将“数量”一词全部替换为“计数”,
-
什么是 cs50.h ?是否包含 get/_float(...) 函数的定义?
-
@MCG 查看
cs50的标签信息。它包含一个处理某些基本 IO 任务的库,其理论是它允许学生专注于更重要的事情。就个人而言,我认为这是一个坏主意,因为在 C 语言中这些细节是学生需要学习的重要内容之一。