So I'm writing this program in c++, it asks the user to give a number (base), between 2 and 10 and a number of digits between 1-10, and then takes a number of said digits, cypher by cypher and converts it to decimal.
The weird thing is, this code that follows seems to work for every case except when the base is 5, only failing then in the first iteration of the for loop, when it seems to get the result-1.
For example, base 5, digits 3: number 341 should be: 3*5^2 + 4*5^1 + 1*5^1 = 75 + 20 + 1 in stance, my code gets: 74 + 20 + 1
Tried to check the outcome of: number=number+(digit*pow(base,(i-1)));
and individually, number is 0, digit*pow(base,(i-1)) is 75, but when they add up it saves 74 and I got no clue why this is happening. As I said, the code seems to work fine for every other case I've checked.
Any ideas? Also, don't tell me to use vectors, this one is for classroom and it's got to be done without them. I'm curious to know where the error is too!
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int base,num_digits;
int digit;
int base_number=0,number=0;
do{
cout << "Enter a base(2-10): " << endl;
cin >> base;
}while(base>10 || base<2);
do{
cout << "Enter a number of digits(1-10): " << endl;
cin >> num_digits;
}while(num_digits>10 || num_digits<1);
for(int i=num_digits;i>=1;i--){
do{
if(i==num_digits){
cout << "Enter first digit: " << endl;
cin>>digit;
}
else if(i==1){
cout << "Enter last digit: " << endl;
cin>>digit;
}
else{
cout << "Enter the next digit: " << endl;
cin>>digit;
}
}while(digit<0 || digit>base-1);
base_number=base_number*10+digit;
number=number+(digit*pow(base,(i-1)));
}
cout << "The number " <<base_number<<" on base "<<base<<" corresponds to "<<number<< " on decimal base"<<endl;
return 0;
}