Divide throw 3 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Divide throw 3

Hello, i need to write a programm which reads in a three digit number, then gets the sum of it (2+3+4), and will check if it is dividable by 3. Input: 234 sum= 9 Output= The number is dividable by 3 with a remainder of 0. #include<iostream> #include<cmath> using namespace std; int main () { bool run {true}; while (run) { long num, counter; double sum {0}; cout<< "Type in three numbers "; cin>> num; if (num>=1000) cout<< "Choosen number has more then three digits!!! will calculate anyway\n"; // hab es nicht hinbekommen das das programm hier dann nochmals von vorne beginnt while (num!=0) { counter=num%10; sum+=counter; num=num/10; } cout<< "\n" <<"The sum of the three digits is "<< sum <<"\n\n"; cout<< sum << "Can the sum of digits be divided by 3? " ; // if (sum % 3) // { // cout<< "yes with a remainder of " << (sum%=3) ; // } char answer; cout<< "Run the Programm again? (y/n): "; cin>> answer; run = answer == 'y'; } return 0; }

18th Oct 2019, 3:32 PM
Yippiekayo Romeo
Yippiekayo Romeo - avatar
5 Answers
+ 5
Sorry, but I think I missed the part where you explained the problem? Please save your code and post the link in Description rather than raw text. It's easier to review a code being saved. Here's how to share links just in case you didn't know: https://www.sololearn.com/post/74857/?ref=app
18th Oct 2019, 4:17 PM
Ipang
+ 2
Yippiekayo Romeo The modulo operator % only works with integral types. Your <sum> variable is a double type (floating point type) and that's the cause of the problem. if (sum % 3) // attempt to use binary modulo operator on floating point type (<sum> is a double) You have two choices here, either change the <sum> variable type to an integral type that fits the purpose (short, int, long, long long or their unsigned versions), or alternatively, use `fmod` function which supports modulo operation on floating point types. Reference: http://www.cplusplus.com/reference/cmath/fmod/ Hth, cmiiw
19th Oct 2019, 9:22 AM
Ipang
0
Perfect thank you. about the code, it feels like i dont used the if, while statements correct. Or the order itself isnt that good, any feedback?
19th Oct 2019, 12:27 PM
Yippiekayo Romeo
Yippiekayo Romeo - avatar
0
Sorry, I didn't get what you mean. You have two `if` statements there, one for checking input greater or equal to 1000, and another one for checking remainder of <sum> divided by 3. Which one you mean?
19th Oct 2019, 12:53 PM
Ipang
0
I mean the structure of the whole code, what can I do better. I know which statements I got in my own code
19th Oct 2019, 1:25 PM
Yippiekayo Romeo
Yippiekayo Romeo - avatar