C语言 如何获得数字序列,然后打印最后5?



我试图制作一个程序,将从以0结束的用户获得序列,然后我想打印最后5个数字(不包括0)。

我可以假设用户将在一行中输入所有的数字,并以0结尾。

我写了这段代码,但是有些地方有问题,我想是scanf行出了问题。

输入:

1 6 9 5 2 1 4 3 0

输出:无输出

#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;

printf("please enter more than %d number and than enter 0: n", N);

last_input = 0;
while (last_input<N) {
scanf(" %d", &j);
if (j == '0') {
last_input = N;
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}


printf("The last %d numbers u entered are:n", N); 

for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);    
}
for (j=0; j<last_input; ++j) {
printf(" %d", arr[j]);  
}
return 0;
}

这个比较

if (j == '0') {

没有意义,因为用户将尝试为字符'0'输入整数值0而不是值(例如ASCII 30h或EBCDIC F0h)。

你至少需要写

if (j == 0) {

由于if语句的这些子语句

last_input = N;
break;

this for loop

for (j=(last_input+1); j<N; ++j) {
printf(" %d", arr[j]);    
}

永远不会被执行,也没有意义。

这句话

last_input=-1;

将打乱输出中最后N个元素的顺序。而且,变量last_input的结果值将不正确。

你需要将数组中的元素向左移动一个位置。为此,您可以使用标准C函数memmove的循环。

程序可以如下所示:

#include <stdio.h>
#include <string.h>

int main( void ) 
{
enum { N = 5 };
int arr[N];
printf( "Please enter at least not less than %d numbers (0 - stop): ", N );
size_t count = 0;
for (int num; scanf( "%d", &num ) == 1 && num != 0; )
{
if (count != N)
{
arr[count++] = num;
}
else
{
memmove( arr, arr + 1, ( N - 1 ) * sizeof( int ) );
arr[N - 1] = num;
}
}
if (count != 0)
{
printf( "The last %zu numbers u entered are: ", count );
for (size_t i = 0; i < count; i++)
{
printf( "%d ", arr[i] );
}
putchar( 'n' );
}
else
{
puts( "There are no entered numbers." );
}
}

程序输出可能看起来像

Please enter at least not less than 5 numbers (0 - stop): 1 2 3 4 5 6 7 8 9 0
The last 5 numbers u entered are: 5 6 7 8 9

我根据您的评论做了一些更改,现在它的工作很好!

#include <stdio.h>
#define N 5
int main()
{
int arr[N] = {0};
int last_input, j;

printf("please enter more than %d number and than enter 0: n", N);

last_input = 0;
while (last_input<N) {
scanf("%d", &j);
if (j == 0) {
break;
}
else {
arr[last_input] = j;
}
if (last_input==(N-1)) {
last_input=-1;
}
++last_input;
}


printf("The last %d numbers u entered are:n", N); 

for (j=(last_input); j<N; ++j) {
printf("%d ", arr[j]);    
}
for (j=0; j<last_input; ++j) {
printf("%d ", arr[j]);  
}
return 0;
}

谢谢大家<</div>

相关内容

最新更新