2016-10-04 36 views
-3

我使这部分代码,并希望它打印出来,如下所示:C++如何打印出数组值彼此相邻而不是下方

Element Value 
    0  0 
    1  0 
    2  0 
    3  0 
    4  0 
    5  0 
    6  0 
    7  0 
    8  0 
    9  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; 

} 
+5

不使用你不明白的东西。或者更积极:理解你使用的东西。如果你告诉你的程序打印换行符,它会这样做,如果你不想打印换行符,就不要这样做。 – user463035818

回答

0

打印在一个循环,而不是使用两个循环彼此相邻的值(我改变了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 

除此之外,不需要th e array n;使用您的索引作为索引。