【问题标题】:How to prevent the wrong value entered by the user from getting stored in the variable?如何防止用户输入的错误值存储在变量中?
【发布时间】:2017-06-12 02:18:15
【问题描述】:

我试图通过在 while 循环中使用 if 语句来防止用户在这个简单的 C 程序中输入错误的值。但问题是,每当用户输入错误的值时,它就会存储在变量中,然后将相同的值用于进一步的计算。 这是实际的程序:

#include <stdio.h>
#include <stdlib.h>
/*Program to calculate the marks obtained scored by the class in a quiz*/

    int main()
    {
    float marks, average, total = 0.0;
    int noStudents;
    printf("Enter the total number of students: ");
    scanf("%d", &noStudents);
    int a=1;
    while(a<=noStudents)
    {
        printf("Enter marks obtained out of 20: ");
        scanf("%f", &marks);
        if(marks<0 || marks >20)
        {
            printf("You have entered wrong marks\nEnter again: ");
            scanf("%d", &marks);
        }
        total = total+marks;
        a++;
    }
    average = total/(float)noStudents;
    printf("Average marks obtained by the class are: %f", average);


    return 0;
}

【问题讨论】:

  • 然后将其读入另一个变量并先检查...
  • 您还应该检查并处理来自scanf()的返回,否则如果输入的不是数字(或空格),您将遇到问题。

标签: c if-statement scanf


【解决方案1】:

第一个问题是您的代码不一致。在条件语句体中,你写了

 scanf("%d", &marks);

%d 使用不匹配的参数类型。这会调用undefined behavior。你应该像以前一样使用%f

也就是说,

  • 您在第二次尝试中依赖用户纠正自己,不要那样做。使用循环,只有在你得到一个有效值之后,才能打破它。
  • 在声明average = total/(float)noStudents; 中,您不需要演员表。其中一个操作数 total 已经是 float 类型,因此即使没有显式转换,也会自动提升另一个操作数并进行浮点除法。

【讨论】:

    【解决方案2】:

    稍微调整了您的代码。希望能帮助到你。正如评论之一中已经提到的,不要期望用户在超出范围的情况下给出正确的值。您应该继续要求用户在范围内输入,除非他输入正确的值。

    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
        float marks, average, total = 0.0;
        int noStudents;
        printf("Enter the total number of students: ");
        scanf("%d", &noStudents);
        int a=1;
    
         while(a<=noStudents)
         {
            printf("Enter marks obtained out of 20: ");
            scanf("%f", &marks);
            if(marks<0 || marks >20)
            {
                printf("You have entered wrong marks.Enter again:\n ");
                continue;
            }
            total = total+marks;
            a++;
         }
        average = total/noStudents;
        printf("Average marks obtained by the class are: %f", average);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 2014-02-14
      • 2012-05-28
      • 1970-01-01
      • 2019-09-05
      相关资源
      最近更新 更多