【发布时间】:2013-10-16 22:33:09
【问题描述】:
前几天刚开始用C编程,有几个问题:
以下程序将摄氏度转换为华氏度,反之亦然。我收到分段错误错误。
#include<stdio.h>
#include <string.h>
#include<stdlib.h>
float c2f(float);
float f2c(float);
float Fahrenheit,Celsius;
int main(int argc, char *argv[])
{
/**
* Check for the expected number of arguments (3)
* (0) program name
* (1) flag
* (2) temperature
*/
if (argc!=3)
printf("Incorrect number of arguments");
if (!strcmp(argv[1], "->f"))
{
// convert the string into a floating number
char *check;
float Celsius = strtod(argv[2], &check);
// process from celsius to fahrenheit
Fahrenheit = c2f(Celsius);
printf("%5.2f°C = %5.2f°F",Celsius, Fahrenheit);
}
else if (!strcmp(argv[1], "->c"))
{
// convert the string into a floating number
char *check;
float Fahrenheit = strtod(argv[2], &check);
// process from fahrenheit to celsius
Celsius = f2c(Fahrenheit);
printf("%5.2f°F = %5.2f°C", Fahrenheit, Celsius);
}
else
printf("Invalid flag\n");
} // main
float c2f(float c)
{
return 32 + (c * (180.0 / 100.0));
}
float f2c(float f)
{
return (100.0 / 180.0) * (f - 32);
}
另外,我希望我的输出是这样的:
**> 温度转换器 ->f 10.0
10.00°C = 50.00°F**
这应该将 10C 转换为 F。
对于 F 到 C,输出应该是:
温度转换器 ->c 50.0
50.00°F = 10C**
【问题讨论】:
-
现在是时候阅读警告/错误消息并在发布到 SO 之前尝试自己完成工作了。如果诸如“函数‘strcmp’的隐式声明”之类的警告让您感到困惑,请发布一个简化的程序,否则看起来您肯定是在让 SO 承担大部分工作。
-
嘿 chux,我 4 天前才开始用 C 编程,但我仍然对错误感到很困惑。
-
这不是你在发布问题,而是你没有展示你解决问题的能力。与其发布带有多个错误的整个代码并说“我不知道为什么”,不如询问有关代码选择方面的具体问题。表明您在 SO 停留之前也曾尝试研究并找出答案。
-
我已经研究并完成了我的整个代码的编写。只是我遇到了一些错误,我不知道为什么会遇到这些错误以及如何解决它们。如果您对如何修复 printf 错误以及我为什么得到它有任何想法,您将非常有帮助。
-
*4天前开始用C编码,只是说。
标签: c converter temperature