c - 为程序添加出口后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;
}
解决方案
为什么我的计算不起作用?
代码在其他地方很好地解决了各种技术问题。
以为我会提到一些数字问题。
要将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);
推荐阅读
- javascript - Typeahead basics example没有给出任何建议,代码与示例相同
- html - HTML 网页中的布局
- reactjs - 添加 Redux 后打包 Electron React 应用程序时无法调试错误,但在开发中完美运行
- azure-machine-learning-service - Azure ML:在模型部署期间包括其他文件
- java - 为什么我的程序使用 Java AOT 比传统的 java 执行慢
- java - Java 构造函数和线程安全
- c# - 在 ASP.NET Core 应用中获取 Azure Insights 遥测数据/搜索日志
- python - 无法使用抽象方法 fetchImageURL、fetchPrice、fetchStockHighLow 实例化抽象类 IEXStockFetcher
- shopify - 如何在电子邮件模板中按产品类型对 Shopify 产品进行排序?
- swift - 快速结束对 Firebase 的观察