也许这里有语法问题?

时间:2014-10-15 21:47:56

标签: c++ syntax

家庭作业问题我正在帮助我的一个受训者(查看我的历史,我之前已经在更高级的程序中请求过Java的帮助。这很简单,我无法帮助她弄清楚)。我们需要使用while循环来读入数字,跟踪计数,并总结输入的数字。我们在第24行继续收到错误。即使我将其注释掉并运行它,程序也不会按预期执行操作。自从我用C ++完成一个程序以来,我一直都需要你的帮助!

#include <iostream>
using namespace std;
int main()
{
    int num;
    int sum = 0;
    int count = 0;
    float avg;

    cout << "Enter numbers, 999 to quit" << endl; 
    cin >> num; // 

    while (num != 999) 
    {
        cout << "Number entered is" <<  num << endl;
        cout << "Enter numbers, 999 to quit" << endl;
        cin >> num;
        sum = sum + num;
        count++;
}
    cout << "Total numbers entered: " + count << endl;
    cout << "Sum of numbers entered is " + sum << endl;
    avg = sum/count;
    cout << "Average of numbers entered:" + avg << endl;



    return 0;




}

2 个答案:

答案 0 :(得分:1)

cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;

+更改为<<

cout << "Total numbers entered: " << count << endl;
cout << "Sum of numbers entered is " << sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" << avg << endl;

答案 1 :(得分:0)

#include<iostream>
using namespace std;

int main()
{
    int num,count;
    float sum,average;

    cout << "Enter numbers, 999 to quit" << endl;
    cin>>num;
    count=0;
    sum=0;


    while (num!=999)
    {
        cout<<"Number entered is"<<num<<endl;
        ++count;
        sum+=num;
        cout << "Enter numbers, 999 to quit" << endl;
        cin>>num;
    }
    if (count==0) {
        count=1;
    }// if the first number you enter is 999 count should be 1 
     // , otherwise avg will be (sum/0 ),which doesn't make sense.

    cout << "Total numbers entered: " <<count << endl;
    cout << "Sum of numbers entered is " <<sum << endl;
    average = sum/count;
    cout << "Average of numbers entered:"<<average << endl;
// use << not + because "Total..." is string type and count is int type
    system("pause");
    return 0;
}

当你做某事时,你应该注意变量的类型,这通常会导致很小的错误。