gpt4 book ai didi

计算热指数的 C++ 程序未提供预期结果

转载 作者:行者123 更新时间:2023-11-30 01:21:56 25 4
gpt4 key购买 nike

我正在编写一个简单的程序来计算热指数。当我运行它时,它应该检查 Temp 是 Fahrenheit 还是 Celcius,然后输出 Heat Index。如果 Temp 低于 80 度,它应该输出“no heat index”。现在它正在输出“所有输入都没有热指数。

之前,它输出的是 -40。为了一切。很难找出这里出了什么问题。

#include <iostream>
#include <string>

using namespace std;

void calcheatIndex (float temp, float humidity); // function to execute HI formula
void inputWeather (float temp, float humidity); // function to get data from user
bool moreTemps (); // ask if user wants to calculate more
void temptype (); // F or C

int main () {
float temp = 0;
float humidity = 0;
float heatIndex;

inputWeather(temp, humidity);
calcheatIndex (temp, humidity);

return 0;
}

void inputWeather(float temp, float humidity) {
cout << "Enter temperature: ";
cin >> temp;
cout << "Enter humidity: ";
cin >> humidity;
while (humidity <= 0) {
cout << "Humidity should be greater than 0. ";
cin >> humidity;
}
}

bool moreTemps () {
string answer;
cout << "Calculate another (Y/N) ? ";
cin >> answer;
while (answer != "Y" && answer != "y"
&& answer != "N" && answer != "n") {
cout << "Answer Y/N : ";
cin >> answer;
}
if (answer == "Y" || answer == "y") {
return true;
}
return false;
}

void calcheatIndex (float temp, float humidity) {
const double c1 = -42.379;
const double c2 = 2.04901523;
const double c3 = 10.14333127;
const double c4 = -.22475541;
const double c5 = -0.00683783;
const double c6 = -0.05481717;
const double c7 = 0.00122874;
const double c8 = 0.00085282;
const double c9 = -0.00000199;

double heatIndex = c1 + (c2 * temp) +
(c3 * humidity) +
(c4 * temp*humidity) +
(c5 * (temp*temp)) +
(c6 * (humidity * humidity)) +
(c7 * (temp * temp) * humidity) +
(c8 * temp * (humidity * humidity)) +
(c9 * (temp * temp) * (humidity * humidity));

string type;

cout << "Is this temperature Fehrenhiet or Celcius (F/C) : ";
cin >> type;
while (type != "F" && type != "f" &&
type != "C" & type != "c") {
cout << "Enter F or C :";
cin >> type;
}

if ((type == "F" || type == "f") && temp >= 80.0) { // Fahrenheit and over 80`
cout << heatIndex;
} else if ((type == "C" || type == "c") && temp >= 26.67) {
heatIndex = heatIndex * 9.0 / 5.0 + 32;
cout << heatIndex;
} else {
cout << "no heatIndex" ;
}
}

最佳答案

问题在于 inputWeather 按值获取其参数:

void inputWeather(float temp, float humidity) {

这意味着当函数更改两个变量时,更改不会传播到调用方。因此,calcheatIndex 总是在 temphumidity 都设置为零的情况下调用。

解决这个问题的一种方法是通过引用获取参数:

void inputWeather(float& temp, float& humidity) {

(别忘了也更改原型(prototype)。)

关于计算热指数的 C++ 程序未提供预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17328034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com