c++ - std::cout 不输出任何内容
问题描述
我正在阅读 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;
}
解决方案
您的代码的问题在于它一直在循环等待输入。我对其进行了一些更改,以询问要输入多少值,以便您检查输出是否实际工作。
#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;
int ntemp;
std::cout << "Enter the number of temperatures to input:";
std::cin >> ntemp;
std::cout << "Please enter " << ntemp << " doubles"<< '\n';
for (int i = 0; i < ntemp; ++i)
{
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;
}
推荐阅读
- image - 在颤动中将图像转换为base64
- sql-server - SSDT 将 2 列添加到表的末尾会导致表重建
- android - 如何复制类似 Photoshop 的功能来保存和恢复 UI 布局?
- python - 如何将 Pandas DataFrame 的每一行转换为新的 nxm 矩阵?
- java - 如何通过同一个开关对启用和禁用 Wifi、移动数据和 GPS 进行编码?
- javascript - 文件协议下的 JS 存储有什么替代方案吗?
- javascript - 想要仅使用 JavaScript 触发触发点击事件
- android - 如何覆盖/重置 android EditText 默认颜色?
- android - 如何在 Exoplayer 中流式传输 .m3u8 视频文件?
- django - 按日期时间月__gte过滤的Django不起作用