繁体   English   中英

如何在输出中添加空格

[英]How to Add Space in Output

数组大小 <=1000 并在 C 编程中反转数组 & 问题正在打印中。

例如输出是:

7654321

我想要:

7 6 5 4 3 2 1

第一行输入有关数组中元素数量的输入。 第二个打印数组的反向。

#include <stdio.h>

int main()
{
    int k, i;
    scanf("%d",&k); //no of integers in array
    int a[1000];    //size given in question 
    for(i=0;i<=1000;i++)//accepting input
        scanf("%d",&a[i]);
    for(i=k-1;i>=0;i--)//for reversing string 
        printf("%d",a[i]);//my problem
    //code
    return 0;
}

除了您的问题,该程序无效。

程序中声明的数组的有效索引范围是[0, 1000) 然而在这个循环中

for(i=0;i<=1000;i++)//accepting input
    scanf("%d",&a[i]);

您试图访问索引等于 1000 的元素,尽管数组没有这样的元素。

如果您的编译器支持可变长度数组,那么您可以使用用户输入的元素数量声明一个数组。

在这种情况下,程序看起来像

#include <stdio.h>

int main( void )
{
    size_t n;

    printf( "Enter the size of an array (0 - exit): " );

    if ( scanf( "%zu", &n ) == 1 && n != 0 )
    {
        int a[n];

        for ( size_t i = 0; i < n; i++ ) scanf( "%d", &a[i] );

        putchar( '\n' );

        for ( size_t i = n; i != 0; i-- ) printf( "%d ", a[i-1] );

        putchar( '\n' );
    }
}

程序输出可能看起来像

Enter the size of an array (0 - exit): 10

9 8 7 6 5 4 3 2 1 0 

注意printf的调用

printf( "%d ", a[i-1] )
         ^^^  

可以替换为以下两个函数调用

for ( size_t i = n; i != 0; i-- ) 
{
    printf( "%d", a[i-1] );
    putchar( ' ' );
}        

暂无
暂无

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

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