从控制台创建具有值的数组。

时间:2022-09-17 13:32:44

I am trying to create an array by taking value 'n' from the console and create an array with 'n' inits and then again take a value 'r' to work.

我试图创建一个数组,从控制台取值'n'并创建一个'n' inits的数组,然后再取一个值'r'来工作。

so far I wrote

到目前为止我写

int main(){
    int n = 0;
    cin >> n;
    int* a = new int[n];
    for(int i = 0; i< sizeof(a);i++){
       cin >> a[i];
    }
       for(int y = 0; y < sizeof(a);y++){
       cout << a[y] << " ";
       }
    int r = 0;
    cin >> r;
    rotate(a,r);

(the "cout" part is for checking the output of the array)

(“cout”部分用于检查数组的输出)

but no matter I try I would get an array which length doesn't equal the input 'n'. Can anyone give me some advice on it?

但无论如何我都会得到一个长度不等于输入'n'的数组。有人能给我一些建议吗?

Here the outputs for every input from console: (the second row is supposed to be the created array)

这里输入来自控制台的每个输入:(第二行应该是创建的数组)

INPUT

6

1 2 3 4 5 6

3

OUTPUT

1 2 3 4 5 6 3 0 

INPUT

10

-1 -2 3 4 5 -6 7 -8 9 0

5

OUTPUT

-1 -2 3 4 5 -6 7 -8 

INPUT

1

1

1

OUTPUT

1 1 0 0 0 0 135137 0 


INPUT

5

1 2 3 4 5

5

OUTPUT

1 2 3 4 5 -3 135137 0 

Any ideas why those unexplainable numbers at the end?

有什么想法,为什么这些无法解释的数字在最后?

1 个解决方案

#1


0  

As Algirdas said, take a close look at what SizeOf does. Also, you don't really need it. You can make it work like this:

正如Algirdas所说,仔细看看SizeOf是做什么的。而且,你并不真的需要它。你可以这样做:

for(int i = 0; i< n; i++){
   cin >> a[i];
}

As you've got 'n' elements in your array.

因为数组中有n个元素。

Also, I know that most textbooks are really fond of arrays, but please follow Cody Gray's advice!

而且,我知道大多数的教科书都很喜欢数组,但是请遵循Cody Gray的建议!

#1


0  

As Algirdas said, take a close look at what SizeOf does. Also, you don't really need it. You can make it work like this:

正如Algirdas所说,仔细看看SizeOf是做什么的。而且,你并不真的需要它。你可以这样做:

for(int i = 0; i< n; i++){
   cin >> a[i];
}

As you've got 'n' elements in your array.

因为数组中有n个元素。

Also, I know that most textbooks are really fond of arrays, but please follow Cody Gray's advice!

而且,我知道大多数的教科书都很喜欢数组,但是请遵循Cody Gray的建议!