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