mardi 10 janvier 2023

How to create an array with the number of elements that increases with conditions?

I want to create an array whose number of elements starts with one and is incremented by one when a certain condition is met, but when running I find that when the number of elements increases to 8, it no longer increases, why

#include<iostream>
int main()
{
    int a,e,re,n=1;
    int arr[n];
    scanf("%d%d",&a,&e);
    for(int i=0;i<n;i++)
    {
        if(a%e<0) re=a%e-e;
        else re=a%e;
        arr[i]=re;
        a=(a-re)/e;
        if(a!=0) n++;
        else break;
    }
    for(int i=n-1;i>=0;i--) 
    {
        printf("%d",arr[i]);
    }
}

This is a base-converted code, when I convert 3 to negative binary, the result is 111, but when I convert 30000 to negative binary, the result is 011110000, but the correct answer should be 11011010101110000, why

Aucun commentaire:

Enregistrer un commentaire