我正在尝试使array3 [ARRAYSIZE]打印出来而没有前导零。我怎样才能做到这一点?输入为6
123456
7
1234567

#include <iostream>
#include <cmath>
using namespace std;

const int ARRAYSIZE = 20;
void InitNumber(char array[ARRAYSIZE]);
int AddArrays(char array1[ARRAYSIZE], char array2[ARRAYSIZE],char arrayfinal[ARRAYSIZE]);
void OutputNumber(char array[ARRAYSIZE]);

int main()
{
    int i=0;
    char array1[ARRAYSIZE], array2[ARRAYSIZE];
    char array3[ARRAYSIZE];
    bool number = false;

    cout << "Please enter your first number" << endl;
    InitNumber(array1);

    cout << endl << "Please enter your second number" << endl;
    InitNumber(array2);

    AddArrays(array1,array2,array3);

    OutputNumber(array3);
    int sum;


这是问题区域。
   似乎要打印á00000000000008308642而不是8308642。
   哪个循环更适合while或for循环。

    do {
        if(array3[ARRAYSIZE-i] != '0')      // heeeeeeeeeeeeeeeeelp
            number = false;
        else
            number = true;
        sum = i++;
    } while(number == true);


    for(sum; sum <= ARRAYSIZE; sum++){          // Outputs all the terms
        cout << array3[ARRAYSIZE-sum];
    }


    return 0;
}

void InitNumber(char array[]){
    int numberofdigits, numbercount;
    int i;

    cout << "How many digits are in your number? ";
    cin >> numberofdigits;
    numbercount = numberofdigits;


    cout << "Please enter the digits in the number with the LEAST significant first: ";
    for(i = 0; i < numberofdigits; i++){    // Inputs the terms
        cin >> array[i];}


    for(numbercount; numbercount < ARRAYSIZE; numbercount++){
        array[numbercount] = '0';   // Inputs zeros into all other terms
    }

}

int AddArrays(char array1[],char array2[],char arrayfinal[]){
    int array1int, array2int, totalint, error =0, i = 0;
    char totalchar;
    for(ARRAYSIZE; ARRAYSIZE-i >= 0; i++){
        array1int = array1[i] - '0';
        array2int = array2[i] - '0';
        totalint = array1int + array2int + error;
        error = 0;
        if(totalint > 9){
            error = totalint/10;
            arrayfinal[i] = totalint%10;
        }

        else{
            arrayfinal[i] = totalint;
        }
    }
    cout << endl;
    return totalint;
}

void OutputNumber(char array3[]){
    bool number;
    int i=0;
    for(ARRAYSIZE; ARRAYSIZE - i > 0; i++){
        array3[i] = array3[i] + '0';
    }
}

最佳答案

在循环的第一次迭代(i == 0)中,通过访问array3[ARRAYSIZE-i]array3[ARRAYSIZE]超出数组范围。如果所有数字均为零,则应以i = 1开头,还应将&& i <= ARRAYSIZE添加到循环条件中以获得正确的行为。

Demo

09-08 04:39