简体   繁体   English

数组打印出错误的数字

[英]Array prints out wrong numbers

I'm new to C++ and I have to make a program that lets the user enter a specified number of test scores and calculate the average, highest, and lowest scores. 我是C ++的新手,我必须创建一个程序,该程序可以让用户输入指定数量的测试分数并计算平均分数,最高分数和最低分数。 (It doesn't have to check if values are between 1 and 100.) For some reason, when it goes to print out the average score and sum of the scores, it just prints out random exponential numbers that are never the same. (不必检查值是否在1到100之间。)由于某种原因,当它打印出平均分数和分数总和时,它只会打印出从未相同的随机指数。 I haven't gotten to printing out the lowest and highest scores yet since I'm not sure if I'm even doing the average right. 我还没有打印出最低和最高分数,因为我不确定我是否在做平均得分。 Again, I'm new to C++ so I'm sure I messed something up. 同样,我是C ++的新手,所以我确定自己搞砸了。 Here's the code: 这是代码:

#include <iostream>
using namespace std;

int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in

int main () {
    cout << "How many test scores are you entering?" << endl;
     cin >> loopLimit;

     testScores = new double[loopLimit]; //changes array to needed size

     for (int i = 0; i < loopLimit; i++) {
         cout << "Enter test score #" << (i + 1) << endl;
         cin >> *testScores;
     }

    double sum = 0.0;
    double average = 0.0;
    //double max = 0.0; //making these functions later
    //double min = 0.0; 

     sum += testScores[loopLimit];
     average = sum / loopLimit;
     //Sum is here for testing purposes at the moment

     cout << "Sum = " << sum << " Average = " << average << endl;

     return 0; 
}

Example output 1: 示例输出1:

How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 8.29874e-310 Average = 2.76625e-310

Example output 2: 示例输出2:

How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 8.94176e-310 Average = 2.98059e-310

Expected output: 预期产量:

How many test scores are you entering?
3
Enter test score #1
100
Enter test score #2
100
Enter test score #3
100
Sum = 300.0 Average = 100.0

I've been at this all week, and I honestly got nothing at this point. 我已经整整一周都在这儿了,老实说我现在什么都没得到。

OK, let's go over your code. 好的,让我们回顾一下您的代码。

#include <iostream>
using namespace std;

Why are you importing all identifiers in std:: here? 为什么要在std::导入所有标识符? using namespace std; is not recommended. 不推荐。

int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in

Bad: You should avoid global variables unless they're absolutely necessary. 坏:除非绝对必要,否则应避免使用全局变量。 99.9% of the time they're not. 99.9%的时间不是。 These could easily be local variables in main . 这些很容易成为main局部变量。

testScores is not an array, it's a pointer. testScores不是数组,而是一个指针。 Initializing it with {0} is just a weird way of writing testScores = nullptr; {0}初始化它只是编写testScores = nullptr;一种怪异方法testScores = nullptr; .

int main () {
    cout << "How many test scores are you entering?" << endl;
     cin >> loopLimit;

     testScores = new double[loopLimit]; //changes array to needed size

You're using manual memory management here. 您在这里使用手动内存管理。 Not technically wrong, but it would be much easier and less error prone to use a std::vector instead. 从技术上来说并没有错,但是使用std::vector会更容易并且更容易出错。

     for (int i = 0; i < loopLimit; i++) {
         cout << "Enter test score #" << (i + 1) << endl;
         cin >> *testScores;

This line stores every input in *testScores , ie the location pointed to by testScores , which corresponds to the first index of the array allocated by new above. 这条线存储在每个输入*testScores ,即,由位置指向testScores ,其对应于通过分配的阵列的第一索引new的上方。 This means only testScores[0] is initialized (ending up containing the last number the user input), every other index is uninitialized. 这意味着仅testScores[0]被初始化(最后包含用户输入的最后一个数字),其他所有索引testScores[0]初始化。

You should use cin >> testScores[i] instead. 您应该改用cin >> testScores[i]

     }

    double sum = 0.0;
    double average = 0.0;
    //double max = 0.0; //making these functions later
    //double min = 0.0; 

     sum += testScores[loopLimit];

This is an invalid memory access. 这是无效的内存访问。 As testScores points to a dynamic array of size loopLimit , the valid array indices go from 0 to loopLimit-1 . testScores指向大小为loopLimit的动态数组时,有效的数组索引从0loopLimit-1 Therefore testScores[loopLimit] accesses memory past the bounds of the array. 因此, testScores[loopLimit]访问数组边界之外的内存。

Also, it's just one element you're adding here. 另外,这只是您在此处添加的一个元素。 Even if this were a valid array index, this could would still make no sense. 即使这是一个有效的数组索引,也仍然没有任何意义。 You should loop over all array elements here (like your for loop above), or just do this part of the calculation in your other loop. 您应该在这里遍历所有数组元素(例如上面的for循环),或者只在另一个循环中执行这部分计算。 In fact, there's no need to store all numbers in memory if all you're interested in is their sum (which you can compute directly as you're reading the input). 实际上,如果您感兴趣的只是它们的和(您可以在读取输入时直接计算),就无需将所有数字存储在内存中。

     average = sum / loopLimit;

average is computed from sum , which has a garbage value, so it's garbage too. average是根据sum来计算的, sum具有垃圾值,因此也是垃圾。

     //Sum is here for testing purposes at the moment

     cout << "Sum = " << sum << " Average = " << average << endl;

... and this is why you're getting garbage output. ...这就是为什么您得到垃圾输出的原因。

     return 0;

Here you're leaking the memory allocated with new . 在这里,您正在泄漏分配给new的内存。 This is not really a problem in this case because your program is about to exit anyway, but in general you want delete[] testScores; 在这种情况下,这并不是真正的问题,因为您的程序无论如何都将要退出,但总的来说,您需要delete[] testScores; here (unless you use a std::vector , which takes care of cleaning up for you). 在这里(除非您使用std::vector ,它会为您清理)。

}

A couple of things, first the line 几件事,首先

     cin >> *testScores;

is not storing the test scores in an array (I think this is what you want to do) instead at every iteration the new test score is being stored in the first element ie testScores[0], rewriting the old value. 没有将测试分数存储在数组中(我想这是您想要做的),而是在每次迭代时,将新的测试分数存储在第一个元素即testScores [0]中,重写旧值。

Next, The line 接下来,线

sum += testScores[loopLimit]; 

looks outside the array. 看起来在数组之外。 This means that you are looking at a random place in memory which probably has junk in it. 这意味着您正在查看内存中可能有垃圾的随机位置。 That explains why you are seeing random numbers outputted. 这就解释了为什么您看到输出随机数的原因。

Try to fix those two issues. 尝试解决这两个问题。 If you don't need to save the test scores you can away keep a running sum of them, that would eliminate the need to store everything in an array. 如果您不需要保存测试成绩,则可以保留它们的连续总和,这样就无需将所有内容存储在一个数组中。

I don't know why you want to write such a messed up code for just calculating average.But here's my approach. 我不知道为什么要编写这样一个混乱的代码来计算平均值,但这是我的方法。 Since you entered loopLimit value as 3 .So according to your code, sum will contain have the value of sum[3] .That is a garbage value .Since indexing starts with 0 and not 1 .So your sum will have a garbage value and that is the reason why you are getting such incorrect value .I have modified your code and it works fine for me. 由于您将loopLimit值输入为3因此根据您的代码, sum将包含sum[3]的值。这是一个垃圾值 。由于索引从0而不是1开始,所以您的sum将会具有垃圾值和这就是为什么您获得如此不正确的值的原因 。我修改了您的代码,它对我来说很好用。

int loopLimit;
cout << "How many test scores are you entering?" << endl;
    cin >> loopLimit;
 double scores[loopLimit];
 double sum=0.0;
 for (int i = 0; i < loopLimit; i++) 
{
         cout << "Enter test score #" << (i + 1) << endl;
         cin >> scores[i];
    sum+=scores[i];
     }
 double avg=sum/loopLimit;
 cout << "Sum = " << sum << " Average = " << avg << endl;
     return 0; 

Try avoiding using pointers during the early stage of programming as it can really mess up with your brain and can create problems.Try to go for a simple approach. 尝试在编程的早期阶段避免使用指针,因为它确实会弄乱您的大脑并可能造成问题。尝试使用一种简单的方法。

The possible issue is that you're doing this 可能的问题是您正在执行此操作

double* testScores = {0};

which will initialize it to nullptr, potentially letting you read and write garbage data. 它将初始化为nullptr,从而可能使您读取和写入垃圾数据。 What you should use instead is probably a dynamic resizing array such as 您应该使用的可能是动态调整大小的数组,例如

std::vector<double> testScores;

and to add a score to the list 并将分数添加到列表中

double inScore = 0;
std::cin >> inScore;
testScores.push_back(inScore); // This adds to the list of scores.
 #include <iostream>
 using namespace std;

int loopLimit = 0; //number of scores or how many times it will loop
double *testScores = {0}; //array scores are stored in

int main () {

double sum = 0.0;
double average = 0.0;

 cout << "How many test scores are you entering?" << endl;
 cin >> loopLimit;

 testScores = new double[loopLimit]; //changes array to needed size

 for (int i = 0; i < loopLimit; i++) {
     cout << "Enter test score #" << (i + 1) << endl;
     cin >> testScores[i];
     sum += testScores[i];
}

 average = sum / loopLimit;

 cout << "Sum = " << sum << " Average = " << average << endl;
 delete [] testScores;
 return 0; 
}

*melpomene is right...that pointer " testScores" wont increment through your for loop so the array occupies garbage also put sum += testScores[i] in the loop to sum your input. * melpomene是正确的...指针“ testScores”不会在for循环中增加,因此该数组占用的垃圾还会在循环中加上sum + = testScores [i]以求和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM