我的输出示例:https://imgur.com/a/nAU41 我正在尝试制作一个简单的F到C构造函数类型程序。每次我运行它,我得到的响应为0.很多问题人们问这个类型的程序有什么问题,他们没有加倍他们(5/9)我已经做了这个但仍然得到回报'0'。
/* Mr. Gadaffi
04.27.17 farenheit to celsius program
*/
#include <iostream>
using namespace std;
// 1.8 * cel + 32;
// 0.55555 * (far - 32);
double fToC(double tempInFarenheit) {
double farenheit, celsius;
farenheit = 1.8 * (celsius + 32);
return farenheit;
}
double cToF(double tempInCelsius) {
double farenheit, celsius;
celsius = (5/9.0) * (farenheit - 32);
return celsius;
}
int main () {
string typeOfDegrees;
double farenheit, celsius;
cout << "Please enter whether your initial degrees are in Farenheit or Celcius(F or C): " << endl;
cin >> typeOfDegrees;
if (typeOfDegrees == "F") {
cout << "What is the degrees in Farenheit?: " << endl;
cin >> farenheit;
cout << "The temperature in Celsius is: " << celsius << " degrees C" << endl;
celsius = fToC(farenheit);
}
else if (typeOfDegrees == "C")
{
cout << "What is the degrees in Celsius?: " << endl;
cin >> celsius;
cout << "The temperature in Farenheit is: " << farenheit << " degrees F" << endl;
farenheit = cToF(celsius);
}
return 0;
}
答案 0 :(得分:6)
在C / C ++中,指令按顺序执行。这意味着,在函数内部,X行在X + 1行之前完成。在你的情况下
double celcius;
// ...
cout << "The temperature in Celsius is: " << celsius << " degrees C" << endl;
celsius = fToC(farenheit);
因此,您首先将celcius发送到cout
,然后然后计算celcius
。您可能想要切换这些行:
celsius = fToC(farenheit);
cout << "The temperature in Celsius is: " << celsius << " degrees C" << endl;
同样的事情为celcius - &gt;华氏转换。
((我知道有很多人喜欢谈论'未定义的行为',问题是否关心这是什么。所以我会提到,作为一个“好的SO用户”,使用变量“避风港”初始化是未定义的行为。))
此外,您的函数cToF
和fToC
不使用参数值。
答案 1 :(得分:4)
double fToC(double tempInFarenheit) { // you forget to use your variable
double farenheit, celsius; // you create celsius here
farenheit = 1.8 * (celsius + 32); // so that is 1.8 * (undefined + 32)
return farenheit;
}
double cToF(double tempInCelsius) { // Same here
double farenheit, celsius;
celsius = (5/9.0) * (farenheit - 32);
return celsius;
}
那应该做你想做的事:
double fToC(double tempInFarenheit) {
double farenheit, celsius;
farenheit = 1.8 * (tempInFarenheit+ 32);
return farenheit;
}
double cToF(double tempInCelsius) {
double farenheit, celsius;
celsius = (5/9.0) * (tempInCelsius- 32);
return celsius;
}
也:
if (typeOfDegrees == "F") {
cout << "What is the degrees in Farenheit?: " << endl;
cin >> farenheit;
cout << "The temperature in Celsius is: " << celsius << " degrees C" << endl; // you send the message here out
celsius = fToC(farenheit); // and here you are calculating it... that can't work
这样:
if (typeOfDegrees == "F") {
cout << "What is the degrees in Farenheit?: " << endl;
cin >> farenheit;
celsius = fToC(farenheit);
cout << "The temperature in Celsius is: " << celsius << " degrees C" << endl;
}
答案 2 :(得分:1)
仅供参考,以上内容可以缩短:
double fToC(double tempInFarenheit) {
return (5/9.0) * (tempInFarenheit - 32);
}