[英]Strange behavior of a int variable
我已經編寫了一個C程序來計算輸入中給定的十進制數的二進制數,但是由於用於保持輸入中給定數的變量而引起的問題很大。
這是我的代碼:
int main() {
// variables declaration
int n,a,i=0;
int vector[i];
float rest;
// acquisition of the input number
printf("enter an integer:...");
scanf("%d",&n);
while(n>0) {
// calculation and comparison of the data acquired to obtain the binary output
rest=n%2;
if (rest!= 0) {
vector[i]=1;
}
else if (rest== 0) {
vector[i]=0;
}
n=n/2;
i++;
}
// representation of the binary value calculated
printf("the binary value of the number entered is: ");
for(a=i-1;a>=0;a--) {
printf("%d",vector[a]);
}
return 0;
}
問題是,如果我輸入的數字大於或等於1024,則二進制數字將是錯誤的。 因此,使用調試工具,我發現問題出在n變量中,恰好在n=n/2
指令中。
如果將1024作為輸入數字,則n=n/2
可以正常工作,直到程序達到n的4值為止,對於該值, n=n/2
指令無效,並將n的值設置為0。
所以我被困在這里,我不知道這是什么問題。
int n,a,i=0;
int vettore[i];
vettore
是一個可變長度的數組。 它的長度是在定義時確定的。 稍后更改i
的值對vettore
。
零長度數組無效,但是對於VLA,不能(必須)在編譯時進行診斷。 由於vettore
沒有元素,因此嘗試為任何元素分配值可能會破壞其他變量。
沒有遍歷整個代碼。 但是您聲明了int i=0
和int vettore[i];
但是在while循環內部,您要遞增i
並修改vettore[i]
,這既危險又錯誤。 (編輯)
您可以嘗試這樣。
int vettore[i];
---> int vettore[100]; // just to work in some cases binary upto length of 100 bits
int vettore[100]; // just to work in some cases binary upto length of 100 bits
非常感謝你們,我已經完成了建議的更改,並且一切正常! 我唯一需要做的就是將變量i初始化為0並將向量初始化為100!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.