我正在尝试将array3 [ARRAYSIZE]打印出来,没有前导零。我怎样才能做到这一点? INPUTS是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';
}
}
答案 0 :(得分:1)
在循环的第一次迭代(i == 0
)中,您通过访问array3[ARRAYSIZE-i]
,即array3[ARRAYSIZE]
来超出数组边界。您应该从i = 1
开始,并在循环条件中添加&& i <= ARRAYSIZE
,以便在所有数字都为零时获得正确的行为。