确定数字是否包含用于班级分配的数字 [英] Determine if a number contains a digit for class assignment

查看:66
本文介绍了确定数字是否包含用于班级分配的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个名为 containsDigit 的函数,该函数确定数字是否包含特定数字.

Write a function named containsDigit that determines if a number contains a particular digit.

标题应类似于:

bool containsDigit(int number, int digit);

如果数字包含数字,则该函数应返回 true .否则,该函数应返回 false .

If number contains digit, then the function should return true. Otherwise, the function should return false.

Input: 
147 9

Output: 
false

我不知道为什么当我这样写的时候总是会出错:

I don't know why I always get false when I write like this:

bool containsDigit(int number, int digit);

int main() {
  double con;
  int number, digit;
  cout << "Input a number and a digit:\n";
  cin >> number >> digit;
  con = containsDigit(number, digit);
  cout << con;
  return 0;
}

bool containsDigit(int number, int digit) {
  int a(0), b;
  b = number;
  while (number > 0) {
    a = a + 1;
    number = number / 10;
  }
  cout << a;
  while (a > 1) {
    a = a - 1;

    if (b / pow(10, a) == digit) {
      cout << "true\n";
      break;
    } else {
      if (a == 1)
        cout << "false\n";
      else
        cout << "";
    }
    b = b % pow(10, a);
  }
}

推荐答案

解决问题的关键是不要跳到代码,首先问自己,我如何提取数字?

Breaking the problem down is the key do not jump to code, start off by asking yourself, how do I extract digits?

运算符与 10 一起使用.那就是您的当前号码%10 .为什么选择 10 ?没有其他号码吗?-除法后,我们需要得到余数,这就是 modulo 运算符执行的其他任何操作.切下来,在计算器上尝试一下.

Use the % operator with 10. That's your current number % 10. Why 10? and not any other number? - We need to get the remainder after division which is what the modulo operator does any other number doesn't cut it, try it on a calculator.

到目前为止,一切都很好,现在您还需要做什么?您需要继续搜索并比较其余数字. 147%10 已经给了您 7 ,并且您要查看 14 ,将14与7分开,然后除以10,得到剩下的部分不包括7.您继续扫描,直到找到数字或数字不足为止.这是一个问题,需要跟进,您的代码是否可以处理负数?,我会留给您自己找出答案.

So far so good, now what else do you need to do? You need to move forward in your search and compare the remaining digits. 147 % 10 already gave you 7 and you want to look at 14, to separate 14 from 7 you divide by 10 and get the remaining part not including 7. You continue your scan till you either find the number or are out of numbers which is the result. There is a problem here, a follow up, does your code work for negative numbers? I will leave that up to you to figure out.

我们剩下以下代码,

bool containsDigit(int number, int digit)
{
    while (number != 0)
    {
        int curr_digit = number % 10;
        if (curr_digit == digit) return true;
        number /= 10;
    }

    return false;
}

这篇关于确定数字是否包含用于班级分配的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆