2017-05-03 91 views
-2

正如标题所说,我不想使用系统(“暂停”),因为我不想开发一个坏习惯。 我不知道为什么它保持关闭,即使我有cin.get();即使我有cin.get();为什么我的应用程序关闭?

#include <iostream> 

using namespace std; 


float medel(int v[], int n) 
{ 
    float res = 0.0; 

    for (int i = 0; i < n; i++) 

    { 
     cin >> v[i]; 

     res += ((double)v[i]/n); 
    } 

    return res; 


} 

int main() { 
    const int num = 10; 
    int n[num] = { 0 }; 

    cout << "Welcome to the program. Enter 10 positive numbers: " << endl;; 
    cin.get(); 
    cout << "The average of ten numbers entered is: " << medel(n, num) << endl; 
    cin.get(); 
    return 0; 
} 
+0

char x,while(x!='q'){cin.get();} –

+3

你是如何学习C++的? 'cin.get();'不会读取10个数字,也不会将其读入任何东西。听起来你可以使用[良好的C++书](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver

回答

4

cin.get()从输入流中消耗单个字符。

如果在那里没有,程序将阻止等待一个,这是你的期望。

然而,有一个存在:从换行符你最后cin >> v[i]手术后回车按键

Don't use cin.get() to keep your application running at the end, anyway

顺便说一句,你的程序的逻辑是有缺陷的;你似乎会提示输入正数,然后在实际询问任何输入之前引入输出。

怎么是这样的:

int main() 
{ 
    const int num = 10; 
    int n[num] = { 0 }; 

    cout << "Welcome to the program. Enter " << num << " positive numbers: " << endl; 
    const float average = medel(n, num); 
    cout << "The average of the numbers entered is: " << average << endl; 
} 

找到一种方法你的程序,以保持终端窗口打开,如果它是不是已经之外。这不是你的计划的工作。

+0

我推荐使用'cin.ignore',如'cin.ignore(100000,'\ n')'。这将忽略字符,直到输入换行符。 –

+2

@ThomasMatthews:我不知道。在这里没有必要使用这样的技巧 –

+0

@BoundaryImposition我想问你,那是漫长的一天。 – RH6

相关问题