【问题标题】:Cs50 greedy without using <cs50.h>cs50贪心不使用<cs50.h>
【发布时间】:2017-06-20 10:04:52
【问题描述】:

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

#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);
}

【问题讨论】:

  • 为什么要在同一个函数中使用名为Cc 的变量?
  • 需要查看scanf("%f", &amp;c);的返回值才能知道是否读取了1个数字。
  • 我使用了两个变量将浮点数转换为整数。我检查了这些值。当我输入数字时它工作正常。但即使我输入字母,我也想得到提示。
  • c=-1;if(scanf("%f", &amp;c) != 1) while(getchar()!='\n');
  • 你期望什么样的输入有什么样的输出?给我们举个例子。

标签: c cs50


【解决方案1】:

在您输入一个不是浮点数的序列后,您期望c 为负数。

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

您需要检查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没有读取到float,它会返回0,你可以继续提示。

演示here

【讨论】:

  • 我错过了需要丢弃字符串的部分,以防不读取浮点数。已编辑并添加。
  • @AjayBrahmakshatriya 您的演示代码有效。谢谢。
  • @BLUEPIXY 我认为这是必需的行为 - 如果输入是否定的,OP 希望重新提示。
  • 我现在检查了。代码工作正常。即使我有同样的问题。但现在它只提示一次。
  • @BLUEPIXY 将操作数的顺序更改为 ||
【解决方案2】:

这是因为浮点数不能接受字符串。当 c 只是一个浮点变量时,您期望它保存其他数据类型。

我建议您将输入作为字符串并使用atof() 来检查输入是否为浮点类型。像这样的:

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    float c;
    int C, nQ, rem1, nD, rem2, nN, rem3;
    char str[10];

    do
    {
        printf("O hai! How much change is owed? ");
        scanf("%s", str);
    }
    while(atof(str) > 0);
    c = atof(str);
    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);
}

这确保您只对浮点数使用 do while 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    相关资源
    最近更新 更多