【发布时间】:2019-10-17 11:57:45
【问题描述】:
我对C不是很熟悉。因此,也许有人会很容易找到解决方案,如果您分享,我不介意。 在第一个 scanf() 中输入数据后,总是给出选项 else(): "Error"。
我一直在寻找解决问题的可能方案。我发现了很多类似的东西,但没有什么能特别帮助我。我认为错误出在 strcmp() 中。但我不能肯定地说。你会帮忙吗?
#include <stdio.h>
#include <string.h>
int main()
{
float celsius, fahrenheit;
char tempConvering[10];
printf("Enter what to convert to what (F to C; C to F): ");
scanf(" %s", &tempConvering[10]);
if(strcmp(tempConvering, "F to C") == 0)
{
printf("\nEnter temperature in Fahrenheit: ");
scanf(" %f", &fahrenheit);
celsius = fahrenheit * 1.8 + 32;
printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
}
else if(strcmp(tempConvering, "C to F") == 0)
{
printf("\nEnter temperature in Celsius: ");
scanf(" %f", &celsius);
celsius = (fahrenheit - 32) / 1.8;
printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
}
else
{
puts("\nError!");
}
}
【问题讨论】:
-
scanf("%s")停在空格处,因此输入“F to C\n”被部分读取为“F”,其余部分留在输入缓冲区中。试试fgets()(记住fgets()也读换行符)。 -
我的建议:永远不要使用
scanf。 -
&tempcovering[10]地址超出数组末尾。就做scanf(" %9s", tempConvering);
标签: c string if-statement scanf strcmp