Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

c++ - Determine if a number contains a digit for class assignment

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

The header should look like:

bool containsDigit(int number, int digit);

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:
";
  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
";
      break;
    } else {
      if (a == 1)
        cout << "false
";
      else
        cout << "";
    }
    b = b % pow(10, a);
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.

We are left with the following code,

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

    return false;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...