【问题标题】:How to use float and double and integer for accurate temperature conversion?如何使用浮点数和双精度数和整数进行精确的温度转换?
【发布时间】:2015-06-29 11:22:15
【问题描述】:

请帮忙。我是编程新手。我现在专注于功能。基本上功能'排序'的作品。然而,从摄氏度转换为华氏温度的温度并不准确。任何关于为什么答案开始正常并且越来越错误的解释都会非常有帮助。谢谢。下面是代码:

#include <stdio.h>
#include <conio.h>

//function prototypes
float convertTofahrenheit(float z);

int main (void){
    float x,y;
    int count_c;
    x=convertTofahrenheit(y);

    printf ("%s\t%s","Celcius","Fahrenheit\n");
    for (count_c=0;count_c<=30;count_c++){
        x++;
        printf ("%d\t%f\n", count_c, x);
    }

    getch();
    return 0;
}

//function for conversion from Celcius to Fahrenheit
float convertTofahrenheit(float z){
    float fahrenheit;
    fahrenheit= ((z*1.8)+32);
    return fahrenheit;
}

【问题讨论】:

  • 您希望在for 循环中发生什么?
  • 这肯定不是您的实际代码。 y 在对 convertTofahrenheit 的调用中未初始化。

标签: c floating-point integer double


【解决方案1】:

将转换放在你的循环中并传入 count_c 转换为浮点数:

float x;  // don't need y
int count_c;

printf ("%s\t%s","Celcius","Fahrenheit\n");
for (count_c=0;count_c<=30;count_c++){
    x=convertTofahrenheit((float)count_c);
    printf ("%d\t%f\n", count_c, x);    
}

因为您只在程序开始时调用 convertTofahrenheit 函数一次,而不是为每个摄氏度值调用一次。

【讨论】:

  • 好的,谢谢。有什么方法可以让函数变得更好,这样我就不必将转换置于循环中?
  • 转换后的值每次增加1.8。因此,您可以只转换第一个值,然后每次通过循环将 1.8 添加到结果中。
  • 不客气。如果答案解决了您的问题,请单击勾选标记将答案标记为已接受。
猜你喜欢
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
  • 2014-02-07
相关资源
最近更新 更多