-
January 24th, 2014, 06:45 PM
#1
2/4 = 0 ?
how come 2/4 = 0? here is the code:
Code:
#include <iostream>
int main()
{
std::cout << 4/2 << '\n'; // == 2
std::cout << 0.25*2 << '\n'; // == 0.5
std::cout << 2/4 << '\n'; // == 0????
std::cin.get();
return 0;
}
Last edited by peteandperry; January 24th, 2014 at 06:48 PM.
Reason: made it look neater
-
January 24th, 2014, 06:59 PM
#2
Re: 2/4 = 0 ?
Originally Posted by peteandperry
how come 2/4 = 0? here is the code:
Code:
#include <iostream>
int main()
{
std::cout << 4/2 << '\n'; // == 2
std::cout << 0.25*2 << '\n'; // == 0.5
std::cout << 2/4 << '\n'; // == 0????
std::cin.get();
return 0;
}
Because when you divide one integer by another, the result is an integer. Since integers can't hold a fractional component and the result is .5, that gets chopped and the result is 0.
To get .5, at least one of the operands needs to be a floating point type, such as
2.0 / 4.
-
January 24th, 2014, 07:09 PM
#3
Re: 2/4 = 0 ?
ohhh ok! i thought it was something along those lines (that it was working like an int) didn't know it was that easy of a fix though. thanks!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|