首页 > 解决方案 > Why does my code put false values in int array?

问题描述

For some reason I get bad output results from this code.

Here I give the code a highest number and a divider number and I check from 0 to highest number all the numbers to see if any of them is dividable with the divider number and if yes, it stores it. I think the problem is at storing data, I just cant figure out why.

#include <iostream>
#include <cmath>

int HN = 200;   //Number of which we look for the dividable numbers
int DN = 3; //The divider number
int STOR[3];   //[(int)floor(HN/DN)];   //Storage of dividable numbers
int VAR = 0;    //Array index

void multiples(int HNt, int DNt){

    for(int i=0;i<HNt;i++){
        if (i%DNt==0){
            STOR[VAR]=i;
            VAR++;
        };
    };
};


int main(){

    std::cout<<floor(HN/DN)<<"\n";

    multiples(HN,DN);

    for(int i=0; i<=VAR-1;i++){
        std::cout<<STOR[i]<<"\n";
    };

return 0;
};

The output I get is

66
0
3
6
73
0
0
0
0
0
0
12
15
18
21
24
27
30
33
...

I excluded the remaining code as it is actually correct up to 198 Any help is much appreciated in advance :)

标签: c++

解决方案


欢迎。

我已经整理了一下,但我自己还是个初学者,所以把它当作一些友好的建议吧!

伊戈尔·坦德尼克说的是正确的。您没有在存储系统中分配足够的空间来记录所有结果。

所以想象一下,你将你的第一个数字写入插槽 0,然后是插槽 1,然后是插槽 2……现在呢?在您的小数组结束后,“堆栈”上可能还有其他数据。您的程序正在使用的其他数据。现在你改写它,创建未定义的结果。然后在几次写入之后,由于这是一个小程序,您可能会在堆栈上找到“空闲”的未使用内存,这就是我猜为什么它似乎会在您进行时为您提供正确的结果。

为什么不使用动态大小的容器进行存储,例如 std::vector?

如果不是至少将您的数组大小与最大可能的结果(即股息)联系起来......见下文。

#include <iostream>
#include <cmath>

//Moved your variables out of the global scope. Lots of reasons for this.

//Take in your parameters as referecnes and a pointer to your storage facility. 
static void multiples(const int& HNt, const int& DNt, int* STOR, int& VAR) 
{ 
   for (int i = 0; i < HNt; i++) {
       if (i % DNt == 0) {
           STOR[VAR] = i;
           VAR++;
       };
   };
};

int main() {
    const int HN = 200; //Made first two const as they do not change
    const int DN = 2; 
    int STOR[HN];   //Const variables can be used to size your array 
                    //This is great because now your array size is linked to the dividend(HN)
    int VAR = 0;  

    std::cout <<"Floor : "<< floor(HN / DN) << "\n";

    multiples(HN, DN, STOR, VAR);

    for (int i = 0; i <= VAR - 1; i++) {
        std::cout << STOR[i] << "\n";
    };

    std::cin.get(); //Stop immediate return to allow displayed results.
    return 0;
}

推荐阅读