c ++如何检查整数中的每个数字并将其与基数进行比较

问题描述 投票:-3回答:2

我无法弄清楚如何将整数中的每个数字分开。基本上,我必须询问用户基数是多少,然后向他们询问两个整数。现在,我的任务是检查以确保两个整数中的每个数字都小于基数(我不知道如何做到这一点!)。

一个例子是这样的:

Enter a base:
3
Enter your first number:
00120
Enter your second number:
11230

我必须检查第一个和第二个数字中的每个数字。第一个数字是有效的,因为所有数字都小于3,第二个数字无效,因为它的3不小于基数。

我花了几个小时试图自己解决这个问题并且没有运气。

c++ integer digits
2个回答
0
投票

如果您要求输入用户,则还没有任何整数。您有文本,您需要做的就是检查文本是否包含有效的数字字符。只要你没有进入大于10的基数,这很简单,因为字符'0' ..'9'必须是连续的并且增加,所以你可以通过从中减去'0'将数字字符转换为其数值。

bool is_valid(char ch, int base) {
    return isdigit(ch) && ch - '0' < base;
}

0
投票

如果您确定输入不包含任何非数字字符,则可以使用%运算符明确检查每个数字。这是我的意思的简单表示:

#include <iostream>

bool isValid(int numb, int base) {
  do  {
    if (numb % 10 >= base) { // if the digit cannot be used with this base
      return false;          // the integer is invalid 
    }
  } while (numb /= 10);

  return true;               // if all the digits passed the above test, 
                             // the integer is valid
}

int main() {
  int numb, base;
  std::cin >> numb >> base;

  std::cout << "input " 
    << (isValid(numb, base) ? "is " : "is not ")
    << "valid " << std::endl;
  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.