【发布时间】:2015-07-02 00:55:49
【问题描述】:
我编写了一个简单的程序,使用函数将华氏度转换为摄氏度(使用 Python 工作了 2 周,想刷新一下自己):
#include <stdio.h>
#include <math.h>
int temp_change(fahrenheit);
int main()
{
while(1)
{
int fahrenheit;
printf("Please input a temperature in Fahrenheit.\n");
scanf("%d", &fahrenheit); //Obtains degrees F value
printf("%d\n", temp_change(fahrenheit));
}
}
//Function to change temperature
int temp_change(fahrenheit)
{
int centigrade;
centigrade = 5*(fahrenheit - 32)/9; //Changing the temperature
return centigrade;
}
它给了我正确的答案(最接近的程度)。但是,我想要确切的答案,所以我将所有的 ints 更改为 floats(int main() 除外。现在程序会给我的唯一的东西是 -18.000000,不管我给它什么输入。
总结我尝试过的最佳方式:我尝试了 ints 和 floats 的不同组合,但没有运气。
我怀疑它与printf("%d\n", temp_change(fahrenheit)); 有关,但是当一切都是int 时,它给了我正确的答案,所以我不知道。 XD
提前感谢您的帮助!
【问题讨论】:
-
很可能您在转换所有数据类型时忽略了更改
scanf()和printf()格式。对于float参数,您需要%f而不是%d。 -
想通了——需要将函数定义中的变量初始化为
float -
@JohnBollinger 谢谢,但不,那会给我一个错误。
-
@JohnBollinger 我正在使用 dev c++,如果我“在转换所有数据类型时忽略了更改 scanf() 和 printf() 格式”会给我一个错误/警告.我需要做的是
float temp_change(float fahrenheit)。看到了吗? -
谁知道用Python两周能有这样的效果。
标签: c floating-point integer temperature