#include <iostream>
using namespace std;
int main() {
// Prompt the user for a decimal number
int decimal_number;
cout << "Enter a decimal number: ";
cin >> decimal_number;
// Prompt the user for the target base
int target_base;
cout << "Enter the target base (2-16): ";
cin >> target_base;
// Validate the target base
if (target_base < 2 || target_base > 16) {
cout << "Error: Target base must be between 2 and 16 (inclusive)." << endl;
exit(1);
}
// Initialize the result string
string result;
// Convert the decimal number to the target base using a while loop
while (decimal_number > 0) {
// Get the remainder of the division by the target base
int remainder = decimal_number % target_base;
// Convert the remainder to a character representation
char remainder_char;
if (remainder < 10) {
remainder_char = str(remainder);
} else {
remainder_char = chr(ord('A') + remainder - 10);
}
// Append the remainder character to the result string
result.push_back(remainder_char);
// Divide the decimal number by the target base
decimal_number /= target_base;
}
// Reverse the result string to get the correct order
reverse(result.begin(), result.end());
// Output the result
cout << "The decimal number " << decimal_number << " in base " << target_base << " is " << result << "." << endl;
return 0;
}
|