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