用户从2-10输入基,然后输入他们想要在基数10中转换的数字。但是,首先,程序检查数字是否在他们输入的基中。
代码:
//ERROR CHECKING FOR DIGITS/ GETTING PROPER DIGITS INPUT
int digit = 0;
bool checker;
cout << "enter number for conversion: "; //Prompt user for base data
cin >> num;
if (num < base){
checker = true;
}
else{
checker = false;
}
//insert each number of digitN inside the array & check if each value is part of the base
while (checker == false){
int len = (std::to_string(num)).size(); //attain array size
for (int i = 0; i <= (len - 1); i++)
{
digit = num % 10;
if (digit >= base)
{
checker = false;
i = len;
}
else
{
checker = true;
}
num = (num / 10);
}
cout << "enter PROPER number for conversion: "; //Prompt user for base data
cin >> num;
}我似乎在for循环中得到了一个错误。谁能帮我弄清楚逻辑吗。一旦程序接受了一个数字,它就会检查该数字的每一个数字,看看它是否在基中。如果是这样,则检查器将为真,否则为false。
发布于 2014-09-15 04:06:33
这是一个简单的检查。
bool is_valid;
unsigned int digit;
unsigned int x = ( num >= 0 ? num : -num );
do
{
digit = x % 10;
} while ( ( is_valid = digit < base ) && ( x /= 10 ) );您可以使用标准函数abs代替三元运算符。
我使用的不是变量名称检查器,而是名称is_valid。你要用什么名字并不重要。
https://stackoverflow.com/questions/25840614
复制相似问题