简体   繁体   English

C ++ cout有时仅打印

[英]C++ cout only prints sometimes

When I run this program and input, for example, the number 7, the final cout command only works occasionally. 当我运行该程序并输入数字7时,最后的cout命令仅偶尔起作用。 Otherwise, the program exits successfully but the result is not printed. 否则,程序将成功退出,但不会打印结果。 Why is this happening? 为什么会这样呢?

#include <iostream>
#include <cmath>

double treble(double);

int main()
{
    using namespace std;
    cout << "Enter a number:" << endl;

    double numways;
    cin >> numways;

    numways = treble(numways);

    cout << "Your number trebled is: " << numways << endl;

    return 0;
}

double treble(double n)
{
    return n * 3;
}

try with this => put 试试这个=>放

int temp;
cin>>temp;

before return 0; return 0;之前return 0; to pause the program, because the execution finished (successfully) before the last output could be written to the console. 暂停程序,因为(最后一次)执行成功完成(可以成功),然后才可以将最后一个输出写入控制台。

You should put using namespace std; 您应该using namespace std; outside of all function declarations, right under your #include directives. 在所有函数声明之外,就在您的#include指令下。 Also, when you say it's not printing, is it that the console is closing before displaying your result? 另外,当您说它不在打印时,是不是在显示结果之前控制台正在关闭? In that case, I would advocate using a simple cin to "pause" the program. 在这种情况下,我主张使用简单的cin来“暂停”程序。 You can do it exactly as @Nihar says, though I might suggest using a string instead of an int so that it doesn't break if you accidentally type something other than an int . 您可以完全按照@Nihar的说明进行操作,尽管我可能建议使用string而不是int这样即使您不小心输入了int以外的内容也不会损坏它。

Something like this: 像这样:

#include <iostream>
#include <cmath>
using namespace std;

double treble(double);

int main(){
    cout << "Enter a number:" << endl;

    double numways;
    cin >> numways;

    numways = treble(numways);

    cout << "Your number trebled is: " << numways << endl;

    string foo;
    cin >> foo;
    return 0;
}

double treble(double n){
    return n * 3;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM