【发布时间】:2015-09-17 17:39:00
【问题描述】:
我刚刚开始学习 C++,我正在通过 Bjarne Stroustup 的 P:P&P 独自工作。
我正在第 4 章练习。
我遇到的问题似乎在于程序的顺序。如果我在向量之前添加另一个右花括号来关闭 while 语句,我会得到max_val 和min_val 的正确输出。但是,通过添加该大括号,名为 sum 的双精度保持为零,即使我希望 sum 增加双命名数字。
如果我按照现在编写的方式编译程序(不添加额外的花括号),我会得到 min_val 和 max_val 的错误输出,但 sum 的正确输出。
此外,正如您在程序底部看到的那样,该行:
cout << " values were entered." << '\n';不完整。我想打印输入的总值,但由于沮丧和需要帮助而使其不完整。我对编程非常陌生,任何建设性的批评,无论多么严厉,都将不胜感激。
#include "std_lib_facilities.h"
int main()
{
double value = 0;
double max_val = 0;
double min_val = 0;
string unit =" ";
double sum = 0;
cout << "Enter some numbers, followed by a unit of distance (m, cm, ft, inch):" << '\n';
while (cin >> value >> unit){
//determines entered value as max/min/both/neither
if (min_val == 0 && value > max_val){ // first number entered is both largest and smallest
max_val = value;
min_val = value;
cout << value << " metres is both the smallest and largest so far" << '\n';
}
else if (value < min_val){// smallest number min_val = value;
cout << min_val << " metres is the smallest so far." << '\n';
}
else if (value > max_val){// largest number max_val = value;
cout << max_val << " metres is the largest so far." << '\n';
}
else { // number between smallest and largest
cout << value << " metres is neither the smallest or largest." << '\n'; }
//convert entered unit to metres
if (unit == "m"){
value = value;
}
else if (unit == "cm"){//converts cm to metres
value = value/100;
}
else if (unit == "ft"){//converts ft to metres
value = value/3.28084;
}
else if (unit == "inch"){//converts inch to metres
value = value/39.3701;
}
else{
cout << "I dont know the unit " << unit << ".";
}
vector <double> numbers; //reads input into vector
double number = 0;
while (cin >> number) numbers.push_back(number);
for (double number: numbers) sum += number;
cout << "The largest value entered was: " << max_val << "." << '\n';
cout << "The smallest value entered was: " << min_val << "." << '\n';
cout << "The sum of the numbers entered is: " << sum << "metres" <<'\n';
cout << " values were entered." << '\n';
keep_window_open("~");
return 0;
}
【问题讨论】:
-
看起来您已经将两个不同的任务混为一谈(距离转换 + 最大/最小/总和)。您遇到问题的实际作业的文本是什么?
-
欢迎来到 Stack Overflow!请edit您的问题与minimal reproducible example 或SSCCE (Short, Self Contained, Correct Example)
-
使用合理的缩进将是一个好的开始。无论如何,你不能随意添加和删除花括号:要么你当前有正确的数字(不管它们的位置),要么你没有,所以当你说你的程序编译但给出不同的输出取决于您是否随机注入“额外”右括号。
-
注意缩进。无论添加额外的花括号,我如何“组织这个程序”以及我可以添加什么以便它完成我想要它做的事情?例如,Chad 说我将两个不同的任务混为一谈。我怎么能把它分开?真的很迷茫。。
-
这如何编译?您使用分号而不是花括号关闭了 main。
标签: c++ vector curly-braces