C ++代码跳过代码,教授无法弄明白

时间:2015-03-24 20:58:42

标签: c++

该程序用于输入一组测试值,对它们进行排序,添加它们并取平均值。最多需要100个变量,并使用负值从输入循环中逃脱。

我和我的教授谈过,大约30分钟后,他仍然无法找到错误。他输入了一些for循环来打印出数组,但它会跳过它们并打印出总数和平均值。

问题在于,当我编译并运行程序时(取决于我使用的编译器),我得到了总计和平均值的奇怪答案,并且它跳过输出数组。这可以通过简单地对sort函数调用注释(或者当然删除它)来解决,但这是一个要求。

例如,Ideone.com给出Total = 0和Average = -nan。

Visual Studio没有给我任何平均值和一个奇怪的答案。

//Programmed by Chandler McLean
//Week 8 Test Scores Lab
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void round(int);
void sortArray(int[ ], int);
int main()
{
  int nums[100] = {0};
  int x = 0, count = 0;
  double z = 0, avg = 0, total = 0;
  cout << "Please enter up to 100 test scores.\nNegative values will terminate program.\nValues above 100 will not be accepted.\n";
  do {
    cin >> x;
    cout << "I just read " << x << endl;
    if (x < 0) {
      break;
    }
    if (x > 100) {
      cout << "Please, tests between 0 and 100 only.\n";
      continue;
    }
    nums[count] = x;
    count++;
  } while (count < 100);

  cout << "...after the loop" << endl;

  for (int i = 0; i < count; i++)
    cout << " array element " << i << " is " << nums[i]  << endl;

  sortArray(nums, count);    // pass array of 20 ints


  for (int i = 0; i < count - 1; i++) {
    total = total + nums[i];
  }
  cout << "\nThe total is: " << total;
  avg = total / count;
  cout << "\nThe average is: " << avg;
  system("pause");
}




void sortArray(int nums[], int count) //store array addr & size
{
  int hold, a, b;               // a and b are subscripts
  for (a = 0; a < count - 1; a++) //start first loop with 0
  {
    for (b = a + 1; b < count; b++) //start second loop with 1
    {
      if (nums[a] > nums[b])    //compare nums[0] to nums[1]
      {
        hold = nums[a];        // if first is bigger
        nums[a] = nums[b];     // swap the two
        nums[b] = hold;
      }
    }
  }
}

1 个答案:

答案 0 :(得分:4)

你的教授一定要很难找出正确的阵列大小。

for (int i=0; i<count; i++){ //not count-1
        total=total+nums[i];
       }
       cout<<"\nThe total is: "<<total; 
       avg=total/count; 
       cout<<"\nThe average is: "<<avg;
       system("pause");
    }