2017-06-20 62 views
-1

我正在解决cs50课程的贪婪算法,而不使用cs50头文件。我写了一个代码。它可以很好地处理数字作为输入,但是当我给它一个字符串或字母作为输入时,它不会提示我回来。我不知道如何解决这个问题。Cs50贪婪而不使用<cs50.h>

#include <stdio.h> 

int main() 
{ 
float c; 
int C, nQ, rem1, nD, rem2, nN, rem3; 

do 
{ 
    printf("O hai! How much change is owed? "); 
    scanf("%f", &c); 
} 
while(c<0); 

C = c * 100; 

nQ = C/25; 
rem1 = C % 25; 

nD = rem1/10; 
rem2 = rem1 % 10; 

nN = rem2/5; 
rem3 = rem2 % 5; 

printf("%d\n", nQ+nD+nN+rem3); 
} 
+1

你为什么要使用一个名为'C'和'C'在同一个函数的变量? –

+0

你需要检查'scanf(“%f”,&c);'来知道是否读取了1个数字的返回值 –

+0

我使用了两个变量来将浮点数转换为整数,我检查了这些值。输入数字,但即使输入了字母,我也想得到提示。 – Laxman

回答

0

您在输入不是浮点数的序列后,会期待c为负数。

这不是一个有效的假设。如果scanf失败,则变量read的值是未定义的。

您需要检查返回值scanf以确定读取是否确实成功。所以你可以改变代码。

int read; 
do 
{ 
    printf("O hai! How much change is owed? "); 
    read = scanf("%f", &c); 

    if (read == EOF){ 
     // Appropriate error message. 
     return -1; 
    } 
    if (read != 1) 
     scanf("%*s"); 
} 
while(read != 1 || c < 0); 

现在,如果scanf不读取浮点数,它将返回0,您可以继续提示。

演示here

+0

我错过了我需要丢弃字符串的部分,以免浮动字符被读取。编辑并添加。 –

+0

@AjayBrahmakshatriya你的演示代码有效。谢谢。 – Laxman

+0

@BLUEPIXY我认为这是必需的行为 - 如果输入是负数,OP希望重新提示。 –