c - 与 scanf() 或 if() 混淆
问题描述
我对C不是很熟悉。因此,也许有人会很容易找到解决方案,如果您分享,我不介意。在第一个 scanf() 中输入数据后,总是给出选项 else():“错误”。
我一直在寻找解决这个问题的可能选项。我发现了很多类似的东西,但没有什么能特别帮助我。我认为错误出在 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!");
}
}
解决方案
#include <stdio.h>
#include <string.h>
int main()
{
float celsius, fahrenheit;
char tempConvering[20];
printf("what do you want to convert? ");
scanf("%s", tempConvering);
if(strcmp(tempConvering, "Fahrenheits") == 0)
{
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit - 32) / 1.8;
printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
}
else if(strcmp(tempConvering, "Celsius") == 0)
{
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = celsius * 9 / 5 + 32;
printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
}
else
{
puts("\nError!");
}
}
这就是答案。我必须感谢您的提示,我会尽量记住有关 scanf() 的所有细节。但是,只有当我将所需的答案更改为“F 到 C”而不是“华氏度”时,问题才消失。好吧,我分别改变了问题。该计划立即获得。然而,尝试用 scanf() 做某事是不成功的,因为 fgets() 会发生同样的事情。
不管怎样,问题总算解决了,谢谢大家!
推荐阅读
- windows - Windows 在管道时将 STDERR 和 STDOUT 重定向到同一程序
- asp.net - Asp.net Identity 用户与模型的关系
- reactjs - react native app中使用Material Ui有用吗
- java - Android Studio - ViewPager 滑块问题
- c - CLion中的灰色光标删除代码,我不知道如何摆脱它
- android - RecyclerView 和 Firebase Storage 快速滚动 ExoPlayer 异常
- r - Rugarch 使用傅里叶级数作为外部回归量
- r - 使用 seq() 中的值的函数
- ubuntu - minikube kompose 无法推送 docker 镜像
- php - 在 PHP OOP 中使用晚餐类中的表 id