C++ 代码跳过代码,教授无法弄清楚

C++ Code skips over code and Professor can't figure it out

本文关键字:代码 弄清楚 C++      更新时间:2023-10-16

此程序用于将输入输入到测试值的数组中,对其进行排序、相加并取平均值。它将使用多达100个变量,并使用负值从输入循环中退出。

我和我的教授谈过,大约30分钟后,他仍然找不到错误。他加入了几个for循环来打印数组,但它跳过了这些循环,打印出了total和average语句。

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

例如,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;
      }
    }
  }
}

教授一定很难算出数组的正确大小。

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");
    }