int 变量的奇怪行为

问题描述 投票:0回答:3

我编写了一个 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 值。

所以我被困在这里,我不知道这是什么问题。

c
3个回答
3
投票
int n,a,i=0;
int vettore[i];

vettore
是一个变长数组。它的长度在定义时就确定了。稍后更改
i
的值对
vettore
没有影响。

零长度数组是无效的,但对于 VLA 来说,它不能(必然)在编译时被诊断。由于

vettore
没有元素,因此尝试为任何元素赋值可能会破坏其他变量。


1
投票

我还没有看完整个代码,但你声明了

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


0
投票

非常感谢你们,我已经完成了建议的更改,一切正常! 我唯一需要做的就是将变量 i 初始化为 0,将向量初始化为 100!

© www.soinside.com 2019 - 2024. All rights reserved.