【发布时间】:2020-11-26 12:50:46
【问题描述】:
我正在阅读 Stroustrup 的书,Programming Principles and Practice Using C++。我可以输入温度,但在控制台中没有得到 std::cout。我没有编译错误。
这里是代码。
#include <iostream>
#include <vector> // I added this which is different from the book
void push_back(std::vector<double> temps, double value) { // I added this which is different from the book, maybe I don't need this but I found it doing a search
temps.push_back(value);
}
int main() {
std::vector<double> temps;
double temp = 0;
double sum = 0;
double high_temp = 0;
double low_temp = 0;
std::cout << "Please enter some integers"<< '\n'; // I added this in for the prompt
while (std::cin >> temp)
temps.push_back(temp);
for (int i = 0; i < temps.size(); ++i) {
if (temps[i] > high_temp) high_temp = temps[i];
if (temps[i] < low_temp) low_temp = temps[i];
sum += temps[i];
}
std::cout << "High temperature: " << high_temp << std::endl; // There is no output for this and the next two lines
std::cout << "Low temperature: " << low_temp << std::endl;
std::cout << "Average temperature: " << sum/temps.size() << std::endl;
return 0;
}
【问题讨论】:
-
什么控制台?您如何编译、运行和查看该程序的输出?
-
您几乎可以肯定是在您的 IDE(开发环境)中运行该程序。这将创建一个窗口,并且程序的输出将定向到该窗口。然后,当程序终止时,窗口被破坏并以足够快的速度消失,以至于您看不到输出。要么找到一种方法在不会立即销毁的窗口中运行程序,要么在
main()的末尾添加一条等待额外输入的语句。 -
void push_back(std::vector<double> temps, double value)您的向量是按值传递的,因此在函数中对其所做的任何更改在函数外部都不可见,因为该对象在函数结束时消失。请改用void push_back(std::vector<double>& temps, double value)。由于您似乎没有使用该功能,所以现在没关系,但如果您将来使用,您应该注意它。 -
还有一件事——像
while(std::cin >> temp)这样的循环会一直循环,直到你输入一些不能是有效双精度的内容(例如,一个字母或一个 EOF 字符(Windows 上的 ctrl+z ))。仅在新行上按 Enter 是不够的。 -
如何传递参数?在交互模式下,
std::cin >> temp会一直阻塞,直到您明确停止输入(某些终端为Ctrl+D)或关闭终端。
标签: c++