[英]C++ getting rid of leading zeros
I'm trying to get array3[ARRAYSIZE] to print out with no leading zeros. 我正在尝试使array3 [ARRAYSIZE]打印出来而没有前导零。 How can i do this?
我怎样才能做到这一点? INPUTS are 6 123456 7 1234567
输入为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;
This is the problem area. 这是问题区域。 Seems to print out á00000000000008308642 instead of 8308642. Which loop is a better fit do while or a for loop.
似乎打印出á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';
}
}
In the first iteration of the loop ( i == 0
) you go out of array bounds by accessing array3[ARRAYSIZE-i]
, that is array3[ARRAYSIZE]
. 在循环的第一次迭代(
i == 0
)中,您通过访问array3[ARRAYSIZE-i]
,即array3[ARRAYSIZE]
超出了数组范围。 You should start with i = 1
, and also add && i <= ARRAYSIZE
to the loop condition to get correct behavior if all digits are zeros. 如果所有数字均为零,则应从
i = 1
开始,并在循环条件&& i <= ARRAYSIZE
添加&& i <= ARRAYSIZE
以获得正确的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.