c - 当用户输入数字以外的任何内容时,如何输出错误?

标签 c input output scanf

因此,当用户键入 1 或 2 以外的任何数字时,程序可以正常运行。它告诉用户您输入了错误的选项并允许用户重新开始。但是,如果用户输入“i”,则它不会显示错误,也不允许用户重新开始。我该如何解决这个问题?

代码如下:

#include <stdio.h>

float celsiusToFahrenheit(float);
float fahrenheitToCelsius(float);

int main()
{
    char ans = 'Y';
    int options;
    float fahrenheit, celsius;

    while(ans == 'Y' || ans == 'y')
    {
        puts("\nEnter an option from the list below(1 or 2).");

        printf("\n1.Celsius to Fahrenheit\n"
               "2.Fahrenheit to Celsius\n\n");
        scanf(" %d", &options);

        if((options == 1) || (options == 2))
        {
            if(options == 1)
            {
                printf("\nEnter Celsius: ");
                scanf(" %f", &celsius);

                printf("\n%.2f Fahrenheit.\n", celsiusToFahrenheit(celsius));
            }
            else if(options == 2)
            {
                printf("\nEnter Fahrenheit: ");
                scanf(" %f", &fahrenheit);

                printf("\n%.2f Celsius.\n", fahrenheitToCelsius(fahrenheit));
            }
        }
        else if((options != 1) || (options != 2))
        {
            printf("\nIncorrect option. Please try again.\n");
        }

        printf("\nDo you want to continue?(Y/N): ");
        scanf(" %c", &ans);
    }

    return 0;
}

float celsiusToFahrenheit(float celsius)
{
    return celsius * 9 / 5 + 32;
}
float fahrenheitToCelsius(float fahrenheit)
{
    return (fahrenheit - 32) * 5 / 9;
}

最佳答案

关于c - 当用户输入数字以外的任何内容时,如何输出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948722/

相关文章:

c - 使用 scanf 获取字符串,然后对该字符串使用 if 语句,而不是 c 语言中的字符

html - 如何使这两个元素彼此相邻

jquery - 单击时,隐藏 div 并删除所需的属性

php - 我想存储来自 html5 input type = "date"元素的值,并希望在数据库中存储完全相同的值

c - 优点 + Vex 皮质 : No response when requesting system info

c++ - 使用 C/C++ 打开和编辑 SVG 文件

c++ - 用大括号初始化 VLA 是 GCC 错误还是扩展?

c++ - 奇怪的文件输出 C++

output - 在 Qbasic 中运行程序时有没有办法保存输出?

powershell - 禁止来自非PowerShell命令的输出?