C++ 代码跳过代码,教授无法弄清楚
C++ Code skips over code and Professor can't figure it out
此程序用于将输入输入到测试值的数组中,对其进行排序、相加并取平均值。它将使用多达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");
}
相关文章:
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 试图弄清楚我需要做哪些更改才能使代码正常工作.使用Visual Studio
- 弄清楚这段代码是怎么回事(递归下降案例研究)
- 我无法弄清楚我的代码未显示预期结果的问题
- 我无法弄清楚我的代码出了什么问题
- 堆排序,我无法弄清楚我的代码出了什么问题,输出顺序不正确
- 我需要帮助弄清楚如何将getline纳入PresentStringPrompt,以摆脱重复的代码
- Visual Studio 2019不活跃的代码没有弄清楚
- 无法弄清楚为什么这个Arduino代码不起作用?
- 我需要帮助弄清楚为什么此C 程序不会使用GNU CC编译器在代码块中构建和运行
- 无法弄清楚如何让G 接受我的代码
- 无法弄清楚为什么代码行会引发异常
- C++ 代码跳过代码,教授无法弄清楚
- 无法弄清楚我自己的代码
- 需要帮助弄清楚此 c++ 代码的计算方式
- C++代码崩溃,无法弄清楚原因
- 无法弄清楚为什么此代码在发送数据包数据时会导致 SIGSEGV
- 我正在阅读开源代码(C++),无法弄清楚为什么他们以这种方式放置枚举
- 我无法弄清楚为什么我的代码无法通过第 60 行的 cin 。帮助??C++
- 无法弄清楚为什么代码崩溃C++