2017-10-21 74 views
2
#include <stdio.h> 
#include <stdlib.h> 

int main() { 
    unsigned int n0; 

    scanf("%d", &n0); 
    const unsigned int n = n0; 
    short unsigned int A[n]; 
    short unsigned int d, x, y, k; 
    short int l, r; 
    int i, j; 

    for (i = 0; i < n; i++) { 
     scanf("%d", &A[i]); 
    } 

    scanf("%d", &d); 
    for (i = 1; i <= d; i++) { 
     scanf("%d %d", &x, &y); 
    } 
    return 0; 
} 

嗨,我是一個總C新手,偶然發現了一個令我驚訝的情況。在上面的代碼中,我想要求用戶輸入一些數字d,然後輸入d對點座標。但令我驚訝的是,程序在輸入第一對(x,y)後結束執行,無論先輸入大於1的d什麼值。如果我在代碼(e.x. d = 5;)中爲d賦值,則不會發生這種情況。可能是什麼原因?通過scanf聲明分配給變量的值是否有所不同,並且不能用於循環條件?環境條件與可變輸入與scanf - C

+0

這是什麼'爲(i = 0; I

+0

@xing,它的工作,謝謝!但爲什麼實際%d沒有按't沒有工作? – jakes

+0

@KrzysztofSzewczyk,這是進一步功能的東西,我忘了在這裏刪除它 – jakes

回答

1

注意編譯代碼時得到的警告。其中一個警告應該如下:

a.c:19:12: warning: format specifies type 'int *' but the argument has type 
    'unsigned short *' [-Wformat] 
scanf("%d",&d); 
     ~~ ^~ 
     %hd 

使用%d原因scanf蒙上了指針short爲指針int,導致不確定的行爲。它看起來像在你的情況下,一個int的上部分存儲在short,而底部部分被丟棄。對於數字undef 2 上部爲零,所以後續循環迭代零次。

修復所有警告將消除這一問題

scanf("%hu", &d); 
... // Fix other scanf calls as well. 

注:沒有爲使循環變量short沒有很好的理由。

+1

感謝您的詳細解釋! – jakes