将摄氏温度转换为华氏温度时出现问题 [英] Problem while converting celsius to fahrenheit

查看:108
本文介绍了将摄氏温度转换为华氏温度时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到的代码输出错误。 

int C,i;
for(i = 0; i< = 300; i = i + 20)
{
C =(5/9)*(i-32);
printf(%d%d \ n,i,C);
}





我的尝试:



但是下面的代码工作正常。困惑为什么它不工作!有帮助吗? 

int C,i;
for(i = 0; i< = 300; i = i + 20)
{
C =(5 *(i-32)/ 9);
printf(%d%d \ n,i,C);
}

解决方案

那是因为你使用的是整数类型,所以得到的是整数除法,剥掉了小部分。

尝试

<前lang =c> float C,我;
for (i = 0 0 ; i< = 300 0 ; i + = 20 0 ){
C =( 5 。< span class =code-digit> 0 / 9 0 )*(i - 32 0 );
printf( %f%f,i,C);
}



这应该有效。

一般来说,对于这样的计算,整数类型是不合适的,因为你需要真实的数字,而不是整数。


正如 phil.o 所指出的,你的问题是整数算术。请注意您的第二个功能不能正常工作(至少不是最准确的)。尝试

  #include   <   stdio.h  >  
#include < math.h >

int op1( int i)
{
return (5/9) *(i- 32 );
}

int op2( int i)
{
return 5 *(i- 32 )/ 9);
}

double dfc( int i)
{
return 5 .0 / 9)*(i- 32 0 );
}

int ifc( int i)
{
return int )round(( 5 .0 / 9)*(i- 32 0 ));
}


int main()
{
int i;
for (i = 0 ; i< = 300 ; i = i + 20)
{
printf( % 3d%3d%5.2f%3d \ n,op1(i),op2(i),dfc(i),ifc(i));
}
}





ifc 函数提供最接近实际实际值的整数结果(近似为 dfc 函数)。


I am getting wrong output for below code.

    int C,i;
    for (i=0;i<=300;i=i+20)
    {
        C=(5/9)*(i-32);
        printf("%d %d\n",i,C);
    }



What I have tried:

but below code works fine. Confused why it is not working! Any help?

    int C,i;
    for (i=0;i<=300;i=i+20)
    {
        C=(5*(i-32)/9);
        printf("%d %d\n",i,C);
    }

解决方案

That is because you are using integer type, so what you get is integer division, which strips away the fractional part.
Try

float C, i;
for (i = 0.0; i <= 300.0; i += 20.0) {
   C = (5.0 / 9.0) * (i - 32.0);
   printf("%f %f", i, C);
}


That should work.
As a general matter, for such computations integer types are not appropriate, because you need real numbers, not integer ones.


As pointed out by phil.o your problem is the integer arithmetic. Please note your second function doesn't work fine (at least is not the most accurate). Try

#include <stdio.h>
#include <math.h>

int op1(int i)
{
  return (5/9)*(i-32);
}

int op2(int i)
{
  return (5*(i-32)/9);
}

double dfc(int i)
{
  return (5.0/9)*(i-32.0);
}

int ifc(int i)
{
  return (int) round((5.0/9)*(i-32.0));
}


int main()
{
  int i;
  for (i=0;i<=300;i=i+20)
  {
    printf("% 3d % 3d % 5.2f % 3d\n", op1(i), op2(i), dfc(i), ifc(i));
  }
}



The ifc function provides the integer result nearest to the actual real value (approximated by dfc function).


这篇关于将摄氏温度转换为华氏温度时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆