+ 1
Division in C++
Such as dividing two numbers where the dividend is less than the quotient. For example, I need to calculate the points a student has earned by attendance. 28 appearances result in 2 points, but if it is less than 28, i need to divide the 2 by 28 to know how many points are gained by presence. In this case the solution I found was to create a constant already with the value of the division, since whenever I try to divide 2 by 28 (2/28) in C++ the result is 0. in this case the solution I found was to creat.
10 Answers
+ 6
Was your question cropped by character limits? in last paragraph => "in this case the solution I found was to creat.". I don't know if this may help, but have you tried using float or double to store the division result?
+ 3
lpang is almost certainly right.
In C or C++, if you divide two integers in the standard way, the remainder will be thrown away, so you're left with the quotient.
e.g.
int a = 12;
int b = 5;
int result = a / b;
In this case, 'result' will equal 2 and not 2.4, because result is an integer variable, so can't store real numbers like 2.4
If you had the code:
int a = 12;
int b = 5;
// Thanks to Gordie for the correction to my code
// Reminding us the importance of code reviews!
double result = (double)a / b;
The 'result' will be 2.4.
2 divided by 28, gives 0 remainder 2 in integer division. As the remainder is usually thrown away in C or C++, your result is therefore zero!
Just try what lpang suggested and use a double to store the result.
Something like:
const double presence_constant = 2 / 28;
I'm not trying to steal the best answer from lpang though. I graciously ask you to give lpang 'best answer'. I merely expanded on their wisdom.
+ 3
@correalinux, Could you post the code link here? maybe if our friends here can see the code things could get clearer, oh also try suggestion by Gordie and Xan : )
+ 2
Ipang Yes, the question was cut. I was saying that the solution was to put the value in a constant rather than calculate and play on a variable.
And yes, too. I have already tried using both Float and Double, both resulting in 0.
+ 2
Thanks Gordie! Well spotted. This is why code reviews are so important.
+ 2
Don't give me best answer...
I'm appreciating the wisdom of everyone else today.
Team work :-)
+ 2
Thank you guys.
It was just the point. I did not know this case, but finally living and learning, I put a ".0" there, and problem solved đ
+ 1
Hurray! This was a great team effort. SoloLearn has a great community!
+ 1
Xan ... True, I'm really enjoying the platform, active community and lots of interaction. This is excellent.
0
Yes, it's the best online programming community ever! :-)