[英]C++ cout only prints sometimes
當我運行該程序並輸入數字7時,最后的cout命令僅偶爾起作用。 否則,程序將成功退出,但不會打印結果。 為什么會這樣呢?
#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;
}
試試這個=>放
int temp;
cin>>temp;
return 0;
之前return 0;
暫停程序,因為(最后一次)執行成功完成(可以成功),然后才可以將最后一個輸出寫入控制台。
您應該using namespace std;
在所有函數聲明之外,就在您的#include
指令下。 另外,當您說它不在打印時,是不是在顯示結果之前控制台正在關閉? 在這種情況下,我主張使用簡單的cin
來“暫停”程序。 您可以完全按照@Nihar的說明進行操作,盡管我可能建議使用string
而不是int
這樣即使您不小心輸入了int
以外的內容也不會損壞它。
像這樣:
#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.