[英]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.