繁体   English   中英

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

[英]c++ how to check each digit in an integer and compare it to the base number

我无法弄清楚如何分隔整数中的每个数字。 基本上,我必须问用户基数是什么,然后问他们两个整数。 现在,我的任务是检查以确保两个整数中的每个数字都小于基数(我不知道该怎么做!)。

一个例子是这样的:

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

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

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

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

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

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

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM