-1

When I run the code below i get this output:

Podaj ilosc liczb: 12

Podaj liczbe nr. 0 : 53

Podaj liczbe nr. 1 : 24

Podaj liczbe nr. 2 : 53

Podaj liczbe nr. 3 : 24

Podaj liczbe nr. 4 : 66

Podaj liczbe nr. 5 : 99

Podaj liczbe nr. 6 : 3

Podaj liczbe nr. 7 : 0

Podaj liczbe nr. 8 : 5

Podaj liczbe nr. 9 : 2

Podaj liczbe nr. 10 : 5

Podaj liczbe nr. 11 : 2 Twoje liczby w odwrotnej kolejnosci: 2 5 2 5 0 3 9 6 2 5 2 5

#include <stdio.h>

int main(int argc, char **argv)
{

char tablo[100];
int k,i;
printf("Podaj ilosc liczb: ");
scanf("%d", &k);fflush(stdin);
for(i=0; i<k; i++){
                 printf("\nPodaj liczbe nr. %d : ", i);
                 scanf("%c", &tablo[i]);fflush(stdin);
                 }
printf("Twoje liczby w odwrotnej kolejnosci: \n");
for(i=k-1;i>=0;i--){
                    printf("%3c",tablo[i]);
                    }
                    printf("\n \n");

return 0;
}

Why? How to fix it? I just want my numbers in the reverse sequence.

4

3 回答 3

1

%c转换说明符告诉从输入流scanf中读取单个字符;当您键入“53”时,只会'5'读取该字符。如果要读取数值并将它们存储在char数据类型中,则需要使用%hhd转换说明符:

scanf( "%hhd", &tablo[i] );

请注意,如果要存储任何大于 128 的值,则需要使用更广泛的数据类型,例如int和适当的转换说明符(%dfor int%hdfor short%ldforlong等)。

不要fflush在输入流上使用,例如stdin; 行为没有定义,它可能不会做你想要的。

于 2014-11-12T18:44:02.793 回答
1

您正在读取和写入单个字符,而不是整数。尝试运行你的程序,比如说,x或者*作为输入;它只会打印您给它的字符,而不会尝试将它们解释为十进制整数。

要读取整数(将序列解释"123"为小数123),请使用scanf("%d", ...)to 读入int对象并printf("%d", ...)打印值 - 并定义tablo为数组 ofint而不是 of char。(并且不要忘记检查返回的值scanf,这样您就可以判断它是成功还是失败。)

并且不要使用fflush(stdin). 输入流上的行为fflush是未定义的,而且你也不需要它。稍后您可能想要一种丢弃无效输入的方法,但这fflush不是答案。

于 2014-11-12T18:26:38.677 回答
0

您只扫描单个字符,而不是实际数字。相反,tablo应该是int(not char) 的数组,而不是使用%cfor scanfand printf,您应该使用%d.

于 2014-11-12T18:24:16.600 回答