【问题标题】:How do you output an error when the user enters anything other than a number? [duplicate]当用户输入除数字以外的任何内容时,如何输出错误? [复制]
【发布时间】:2016-03-01 03:28:10
【问题描述】:

因此,当用户键入除 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;
}

【问题讨论】:

  • 根据this post接受的回答,应该使用fgets()读取,使用sscanf()解析。

标签: c input output scanf


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2018-05-05
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多