我正在嘗試制作一個程式,該程式將從用戶那里獲取以 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;
}
uj5u.com熱心網友回復:
這個比較
if (j == '0') {
沒有意義,因為用戶將嘗試輸入整數值 0 而不是字符“0”的值(例如 ASCII 30h 或 EBCDIC F0h)。
你至少需要寫
if (j == 0) {
由于 if 陳述句的這些子陳述句
last_input = N;
break;
這個 for 回圈
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
uj5u.com熱心網友回復:
我根據您的評論進行了一些更改,現在它作業正常!
#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;
}
謝謝你們<3。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/485087.html
上一篇:C前處理器中的型別檢查