我正在写一个简单的程序来计算热度指数。当我运行它时,它应该检查温度是华氏温度还是摄氏温度,然后输出热量指数。如果温度低于80度,它应该输出“无热指数”。现在,它正在输出“所有输入没有热度指数”。
之前,它的输出是-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" ;
}
}发布于 2013-06-27 02:49:13
问题是inputWeather是通过值来获取参数的:
void inputWeather(float temp, float humidity) {这意味着当函数更改这两个变量时,更改不会传播到调用方。因此,总是在temp和humidity都设置为零的情况下调用calcheatIndex。
解决此问题的一种方法是通过引用获取参数:
void inputWeather(float& temp, float& humidity) {(不要忘记还要更改原型。)
发布于 2013-06-27 02:49:55
C和C++在调用方法时默认按值传递(与按引用传递相对)。
在按值传递时,调用点处的值的副本被传递给函数中的一个新变量;函数的参数形成了一个新的作用域-一个同名的新变量。由于它是一个新变量,因此在inputWeather中对temp和humidity的修改不会反映在main方法的变量中。因此,温度和湿度为零,这意味着没有热指数。(以前,您可能没有初始化温度和湿度,因此它们的值或多或少是随机的。)
在C++中,您可以通过以下签名轻松地将函数更改为按引用传递:
void inputWeather(float &temp, float &humidity) {这将告诉语言使inputWeather中的temp和humidity变量引用与在调用点指定为参数的变量相同的内存位置,以便对函数中这些变量的修改将在调用者的变量中可见。
有关差异的更多详细信息,请参阅What's the difference between passing by reference vs. passing by value?
https://stackoverflow.com/questions/17328034
复制相似问题