首页 > 解决方案 > 为程序添加出口后C代码计算未正确输出

问题描述

嘿伙计们 n gals 第一次海报第一次学习代码。

我敢肯定,当您盯着代码足够长的时间时,我会自然而然地错过一些非常小的东西。为什么我的计算不起作用?我错过了什么?

我可以在不执行 # 退出的情况下让它工作,但我确定我在这里遗漏了一些东西。


#include <stdio.h>
#include <stdlib.h>
int main()
{
char input;
int a,b,c;

while(1)        {
    
    
    printf("\nPlease Enter Temperature in kelvin \n\nThen enter # when you have had enough:\n ");
    scanf(" %c", &input);
    if(input == '#'){
    break;
    }
    
    if(input != '#')                        {



    scanf("%d",&c);
    printf("\n1.Convert to celcius\n2.Convert to fahrenheit\nEnter choice now\n");
    scanf("%d",&a); 


    

    switch(a)           {
    case 1:
    b=(c-273);
    printf("Temperature in celcius is %d\n\n",b);
    break;
    case 2:
    b=((c*9)/5)-460;
    printf("Temperature in fahrenheit is %d\n\n",b);
    break;
    default:
    printf("You selected wrong choice");
    break;                                                              /// End of code here
                        }

                                            }

    getchar ();

                                              
                
                }
    return 0;
                
}

标签: c

解决方案


为什么我的计算不起作用?

代码在其他地方很好地解决了各种技术问题。

以为我会提到一些数字问题。

要将K 转换为 °F

°C = 0K − 273.15
°F = °C×9/5 + 32

用整数数学做到这一点并获得最佳答案

//  (K     − 273.15)×9/5      + 32
//  (K*100 − 27315)×9/(5*100) + 32
// ((K*100 − 27315)×9         + 32×500)/500
// ((K*100 − 27315)×18        + 32×1000)/1000
// above using real math, below using integer C math
// t = (K*100 − 27315)×18 + 32×1000; (t + signof(t)*500)/1000
// More simplifications possible

int t = (K*100 - 27315) * 18 + 32*1000;
t += (t < 0) ? -500 : 500;  // round by adding half the divisor, correctly signed
F = t/1000;

使用 FP 数学来做到这一点并得到一个好的整数答案

#include <math.h>
F = lround((K − 273.15)*9.0/5.0 + 32);

推荐阅读