c++如何打印数组值相邻而不是在下面

C++ how to print out array values next to each other rather than underneath

本文关键字:在下面 数组 何打印 打印 c++      更新时间:2023-10-16

我已经制作了这段代码,并希望它打印出来如下:

元素的值0 01 02 03 04 05 06 07 08 09 0 之前

而不是在彼此的下面。谁能给我指个正确的方向吗?

#include <iostream>
int main(){
    int n[10] = {1,2,3,4,5,6,7,8,9,10};
    int x[10] = {0,0,0,0,0,0,0,0,0,0};
    std::cout << "Element" <<std::endl;
    for(int i = 0; i < 10; i++)
    {
        std::cout  <<n[i] << std::endl;
    }
    std::cout << "Value" <<std::endl;
    for(int y = 0; y <10; y++)
    {
        std::cout  << x[y] << std::endl;
    }
    std::cout << "size of array: " << sizeof(n) << std::endl;
}

在一个循环中打印相邻的值,而不是使用两个循环(我更改了x的内容,以确保我们看到发生了什么):

#include <iostream>
int main(){
    int x[10] = {5,8,1,2,4,6,7,1,0,9};
    std::cout << "Element  Value" << std::endl;
    for(int i = 0; i < 10; i++) {
        std::cout << "    " << i << "     " << x[i] << std::endl;
    }
    std::cout << "size of array: " << sizeof(x) << std::endl;
    return 0;
}
https://ideone.com/vAaLyl

输出:

Element  Value
    0     5
    1     8
    2     1
    3     2
    4     4
    5     6
    6     7
    7     1
    8     0
    9     9
size of array: 40

除此之外,不需要数组n;使用您的索引作为索引