我想知道如何提示我的程序的最终用户输入他们想要在 C 中从华氏温度转换为摄氏温度的值。
基本上,因为我是一个完全的 n00b 并且我正在编写令人惊叹的“程序”,例如这个:
//Simple program to convert Fahrenheit to Celsius
int main (int argc, char *argv[])
{
double celsius, fahrenheit, result;
celsius = result;
fahrenheit = 27;
result = (fahrenheit - 32) / 1.8;
printf("27 degress Fahrenheit is %g degrees Celsius!", result);
return 0;
}
如果您知道我的意思,我想为它添加一些实际的“功能”。我不想让它成为一个测试程序,实际上它只是展示一些简单的算术表达式评估,我想让它实际上有点用处。
无论如何,我想知道是否可以使用scanf(3) 手册页中列出的函数来帮助我识别用户输入的数据,然后以某种方式将其存储到 Fahrenheit 变量中。
现在,如果程序在运行时可以提示最终用户一个问题,询问他或她是想从摄氏温度转换为华氏温度还是从华氏温度转换为摄氏温度,那将是非常酷的,但让我们迈出一步有时间,我会等到我读到我书中关于“做出决定”的章节!:)
更新:
删除 kiamlaluno 指出的无用变量结果:
//Simple program to convert Fahrenheit to Celsius
int main (int argc, char *argv[])
{
double fahrenheit, celsius;
fahrenheit = 27;
celsius = (fahrenheit - 32) / 1.8;
printf("27 degress Fahrenheit is %g degrees Celsius!", celsius);
return 0;
}
更新更新:
我一直在尝试合并每个人在此处发布的有用建议,但我的代码遇到了更多问题:
//Simple program to convert Fahrenheit to Celsius and Celsius to Fahrenheit
int main (int argc, char *argv[])
{
int celsius, fahrenheit, celsiusResult, fahrenheitResult;
celsiusResult = (fahrenheit - 32)*(5/9);
fahrenheitResult = (celsius*(9/5)) + 32;
int prompt;
printf("Please press 1 to convert Fahrenheit to Celsius, or 0 to convert Celsius to Fahrenheit please:\n ");
scanf("%i", &prompt);
if(prompt == 1) {
printf("Please enter a temperature in Fahrenheit to be converted into Celsius!:\n");
scanf("%i", &fahrenheit);
printf("%i degress Fahrenheit is %i degrees Celsius!", fahrenheit, celsiusResult);
}
else {
printf("Please enter a temperature in Celsius to be converted into Fahrenheit:\n");
scanf("%i", &celsius);
printf("%i degreses Celsius is %i degrees Fahrenheit", celsius, fahrenheitResult);
}
return 0;
}
一切都很好,除了计算本身,结果完全错误。有一秒钟我认为这可能是因为我将数字本身更改为整数类型,但我再次将它们加倍,它仍然有点棘手。
有什么想法吗?