I'm trying to take a user input number between 1 and 10 million, break it apart into its individual digits, and then assuming I have the first two digits already as an integer variable, compute what the multiplier would be to get that number back to the same size. I know I'm losing precision by only taking the first two numbers, but ignore that for now.
My problem is I run a loop that breaks the number into its digits, and assign a variable "digits" the value of the loop counter upon exit to represent how many digits the number had.
Then when it calculates the second to last line of the below code, it works fine for any number of digits from 2 through 8, (outputting a multiplier of 100000 for a 7 digit number for instance) with the exception of 4 and 6 digit numbers, where instead of 100 and 10000 I get 99 and 9999...
All my variables are int, so I'm lost as to why this is happening and how to fix it...
cout << "Please enter the resistance in ohms";
cin >> resistance; //gets resistance from user
resistancecount = resistance; //copy into another variable to allow change to determine number of digits for multiplier
while (resistancecount>0) //while loop to determine number of digits in the resistance for multiplier
int length[digits]; //set up array for storing digits so can be assigned within a loop. couldn't initialize
//until after number of digits was fixed
resistanceseparate = resistance; //copy resistance into another variable to pull apart into individual digits
for (i=0; i<digits; i++) //for loop pulls resistance apart into individual digits
lastdigit = resistanceseparate%10;
length[i] = lastdigit;
bandone = length[digits-1]; //sets bandone equal to first integer of resistance
bandtwo = length[digits-2]; //sets bandtwo equal to second integer of resistance
bandthree = pow(10,(digits-2)); //sets bandthree equal to multiplier -- something wrong here for 4 and 6 digit numbers...
cout << bandthree;
Nobody has any ideas?
I'm noticing that in another spot in the program that taking a different variable minus two is causing a similar problem (a variable resulting from pulling resistance apart into it's component digits), but again, only when the resistance variable is 4 or 6 digits long.
You haven't submitted a complete/compilable code snippet. If people recreate your setup, they're very likely to be doing something different than you are, and that may not end in the same result you're having. Please reduce your code to the smallest compilable sample which reproduces the problem when posting. Your code uses VLAs which isn't legal in the current standard.
For instance, the following works fine for me (vla replaced with vector to make it compile:)