【问题标题】:While loop for only accepting integer value and exiting on any other inputWhile 循环仅接受整数值并退出任何其他输入
【发布时间】:2015-12-04 19:27:16
【问题描述】:

我在 C 中运行这个程序来将华氏温度转换为摄氏温度,并且只需要接受来自用户的整数值。

请告诉我如何修改?

int main() {
    int x;
    double y;
    while(x>0) {
        printf("Enter the temperature in Fahrenheit:");
        scanf("%d", &x);
        y=((x-32)/1.8)
        printf("%f\n",y);
    }
}

【问题讨论】:

  • 请在测试之前初始化x(并启用编译器警告)。
  • 首先,while 循环的条件是在变量 x 被赋值之前使用它。如果要检查是否成功读取整数,请使用scanf的返回值

标签: c while-loop


【解决方案1】:

您的代码不起作用的原因是有时scanf 没有读取任何内容,因此它不会修改x

您知道scanf 通过检查其返回值来读取某些内容。它返回“扫描”项目的数量。在这种情况下,号码必须是1

scanf 改为返回0 时,您应该读取并丢弃缓冲区中的数据。您可以通过提供%*[^\n] 格式说明符来完成此操作,这意味着“读取并丢弃最多'\n' 字符的输入。读取int 直到成功的完整sn-p 如下所示:

while (scanf("%d", &x) != 1) {
    printf("Please enter a valid number:");
    scanf("%*[^\n]");
}

注意:不用说,您应该使用在计算 y 的行上缺少的分号 ; 来修复语法错误。

【讨论】:

  • 感谢您的回复,只要我输入整数值,代码就可以正常工作,但是当我输入其他内容时进入无限循环,因此在 while(x>0) 我需要一些表达式这将检查它是否是整数值,如果输入的值不是整数,我需要添加代码以退出。
【解决方案2】:
  • 您可以使用以下代码。

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
     int x;
     double y;
     char str1[5];
    int num1,i;
    bool yes = true;
      while(x>0) 
      {
          printf("Enter the temperature in Fahrenheit:");
          scanf("%s",str1);
          for(i=0;str1[i]!='\0';i++)
          if(!(str1[i]>=48&&str1[i]<=56))
          {
             printf("The value is invalid \n");
             yes = false;
          }
          num1 = atoi(str1);
    
          if(yes == true)
          {
            printf("This Number is %d\n",num1);
            y=((num1-32)/1.8);
            printf("%f\n",y);
           }
       }
    }
    

【讨论】:

  • 使用if(!(str1[i]&gt;='0'&amp;&amp;str1[i]&lt;='9')),代码会更清晰、更不容易出错(并且更正确)。 str1[i]&lt;=56 肯定是不正确的。
  • 1) int x; ... while(x&gt;0) 复制了 OP 未能初始化 x。 2) char str1[5]; ...scanf("%s",str1); 没有正确地将输入限制为 4 个字符。
猜你喜欢
  • 2021-11-28
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多