Hi, I'm a student, finish the first course. Gave 10 tasks, very simple, but one thing I do not quite understand.

The specified non-empty text includes only numbers and letters. Determine whether it satisfies the following property: the text is a decimal notation of a multiple of 9.

Should I work with line items like with numbers? Those. if "123", then this is 1, 2, 3? If so, how?

Knowing that you can work with char as with an int, I did this:

int if_div_by_9 (char str[], int n) { int num = 0; for (int i = 0; i < n; i++) { num = num * 10; num = num + str[i]; } if ((num % 9) == 0) return true; return false; } 

But at the same time, "1" in the line will not be 1. I understand that ASCII code will be used. If you need to work with numbers from a string, then what about letters? I could write a function that returns a pointer to a new array, in which there are no letters, but I still do not know how to work with numbers, but not with their code. And I'm not sure that I understand the condition of this school assignment.

UPD:

 int if_div_by_9 (char str[], int n) { int num = 0; for (int i = 0; i < n; i++) { if ('0' <= str[i] && str[i] <='9') { num *= 10; num += (str[i] - '0'); } } cout << num << endl; if ((num % 9) == 0) return true; return false; } 
  • 1. Check that all characters are digits (std :: isdigit), 2. If the sum of digits is divisible by 9, then the number is a multiple of 9. - αλεχολυτ
  • one
    To convert an ASCII character to a number, subtract the character '0' from the character code (zero code). - αλεχολυτ
  • I would add: either int if_div_by_9(...) { ... return 0; } int if_div_by_9(...) { ... return 0; } (C-code), or bool if_div_by_9(...) { ... return false; } bool if_div_by_9(...) { ... return false; } (C ++ code). Well, 'D' - '0' == D (if D is a digit) is a requirement of the C standard (C ++), i.e. does not depend on the coding. - andy.37

1 answer 1

Your solution (if you bring it to mind) will not work with numbers that are longer than 9-10 characters. Of course, the teacher will enter a much larger string. Let your string be n characters in length. You need to go through it and make sure that all the characters are numbers. You can check that c is a digit by the condition '0'<=c && c<='9' . Then you can add the values ​​of all digits. Or, as you wrote in the comments above, subtract from the value of each character '0' , or simply add all the characters and then subtract n*'0' once. As is known, the sign of divisibility by 9 is the sum of digits divided by 9. That is, the resulting amount and must be checked for divisibility by 9.

In one thing you are right - this is a school assignment, the 5th grade, if measured in our school (extra computer science classes for advanced children). I am very puzzled to see this in high school ... although now everything is possible.

  • one
    Checking for numbers is done with isdigit() . No need for bikes with comparisons. - PinkTux