开发者

Minor sequence error in C++ program output

I am trying to output "states" for any binary number that is inserted (for each 0 it outputs a random number between 1 & max), for example 10100 should output 2, random number between 1 & 2, 3, random number between 1 & 3, random number between 1 & 3. Thus looking like 21323 or 223212 or 21313, etc. But the output my program is giving me is 23456 - why?

int main()
{
    char binaryArray [0];
    int c1=1;
    int c0=0;
    int i=0;
    int n;

    cout << "Enter length of binary: "; //Length = total number of 1s & 0s
    cin >> n; 

    cout << "Enter binary number: ";
    cin >> binaryArray;

    cout << "States: ";

    for(i; i<n; i++)
    {
        if(binaryArray[i]=1)
        {
            c1++;
            cout << c1;
      开发者_StackOverflow  }
        else if(binaryArray[i]=0)
        {
            c0++;
            cout << rand()%c1+1;  
        }
        /* if(c0 > c1)
        {
        cout << "Invalid Binary Representation.\n" << endl;
        exit(0); 
        } */
    }

    system("PAUSE");
    return 0;
}


When you have an array of 0 (that is: zero) characters, you cannot save anything in it, not even a single bit. Make that array "large enough" (whatever that means for you) or better use a std::string instead.

Oh, and compile your code with all compiler warnings enabled. When you have understood and fixed all these warnings properly, you program should work much better. (Hint: assignment inside conditional)


First of all, you have assignment in the if statements. Use == instead of =.

Second, if you expect the number to be entered as binary and stored in char array, use char when comparing. So, your if statements should be:

//                vvvvvvv   
if( binaryArray[i] == '1' )
{
    c1++;
    cout << c1;
}
//                     vvvvvvv
else if( binaryArray[i] == '0' )
{
    c0++;
    cout << rand()%c1+1;  
}

Third, change the size of your array:

char binaryArray [0];

It must not be 0 here. Change it so something more common. Like 512, for example, if you think that this will be big enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜