知识点:
- if … else if … else if … 最后结束可以没有else
- 注意要避免在 while 中写入字符,容易出问题。如果想比如说读入字符 ‘A’ 就结束输入,可以写在 while(1)里面,加一句判断,字符等于 ‘A’ 时候,就 return 0; 一样可以结束输入
- ln(x) 这个函数用c++表示为log(x)。log(x) 就是自然对数。log10(x) 才是以为10底的对数
- setprecision() 可以控制浮点数显示的有效位数。使用一次默认对后文产生相同的影响
setprecision(n)对有效位的保留采取四舍五入。
注意搭配上 fixed 后,setprecision(n)变为保留小数点后的有效位
详情请看:https://blog.csdn.net/qq_42187809/article/details/85395715
(还有一种实现四舍五入保留小数点后几位的方法:https://blog.csdn.net/Jacketinsysu/article/details/52434669)
本题思路挺巧妙,通过判断数字是否被更改,来判断是否写入相应的字符。避免了通过if else … 来进行大量字符的读入判断。所以相应的数字位提前初始化一个数,本题为 1000(因为取值为-100~100),如果该位数值改动,说明对相应的字符进行了写入!
#include <iostream>
#include <sstream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace std;
//const int maxn = 100000 + 10;
int main(){
char alpha;
float num;
while (1) // 避免在 while 中写入字符,容易出问题。
{
float tem = 1000, dew = 1000, sum = 1000; // 重点!!
for (int i = 0; i < 2; i++)
{
cin >> alpha;
if (alpha == 'E')
return 0;
cin >> num;
if (alpha == 'T')
{
tem = num;
}
else if(alpha == 'D')
{
dew = num;
}
else if (alpha == 'H') // if ... else if ... else if ... 最后结束可以没有else
{
sum = num;
}
}
if (tem == 1000)
{
float e = 6.11 * exp(5417.7530 *((1 / 273.16) - (1 / (dew + 273.16))));
float h = (0.5555)*(e - 10.0);
tem = sum - h;
}
else if (dew == 1000)
{
float h = sum - tem;
float e = h / (0.5555) + 10.0;
dew = (1 / ((1 / 273.16) - (log(e / 6.11) / 5417.7530))) - 273.16; // ln(x) 这个函数用c++表示为log(x)
}
else if(sum == 1000)
{
float e = 6.11 * exp(5417.7530 *((1 / 273.16) - (1 / (dew + 273.16))));
float h = (0.5555)*(e - 10.0);
sum = tem + h;
}
cout << fixed << setprecision(1) << "T " << tem << " D " << dew << " H " << sum <<endl;
// fixed 和 setprecision 设置一次就够了,接着的数据都按照这种格式走
}
return 0;
}