簡體   English   中英

std::cout 沒有 output 任何東西

[英]The std::cout does not output anything

我正在閱讀 Stroustrup 的書《使用 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;
}


您的代碼的問題在於它一直在循環等待輸入。 我稍微改變了一下,詢問要輸入多少值,以便您檢查 output 是否實際工作。

#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;
}

您在 output 中看不到任何內容,因為您的程序在執行指令完成后立即終止。 你可以使用 getch(); 或系統(“暫停”); 這樣,程序將需要鍵盤命令。

我在線嘗試了您的代碼,實際上在控制台中獲得了std::cout -prints。 但是,正如 jrok 和 Jarod42 在評論中提到的那樣,用戶必須通過輸入無法解析為雙精度的輸入來終止 while 循環。 再次訪問 Stroustrup 的書(Programming Principles and Practice Using C++)中的第4.6.3 A numeric example 那里說:

我們使用了字符“|” 終止輸入——任何不是雙精度的都可以使用。 在第 10.6 節中,我們討論了如何終止輸入以及如何處理輸入中的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM