Public Group

# Division by zero (C++)

This topic is 4150 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Basically, I have a and b (floats), I add them up and divide by zero - that's c (float). Now, I tell std::cout to print c and it prints 1.#INF Ok, here is my code:
#include <iostream>

int main()
{
float a;
float b;
float c;
std::cout << "type a number" << std::endl;
std::cin >> a;
std::cout << "Great! now type another one" << std::endl;
std::cin >> b;
c = (a (plus) b)/0; //the problem here is that the forum source tags won't display the 'plus sign', but there was suposed to be one here.
std::cout << "c is: " << c << std::endl;
std::cin >> b;
return 0;
}


The strange part is that, if I replace a and b by 1 (but not both by 1.0, then it will work fine), then the compiler will get me an error in Visual C++ Express, and in Code::blocks, it will compile but it will crash. My processor is a Pentium 4, 3.0 Ghz. Does anybody know what's going on?

##### Share on other sites
floats aren't like ints (http://en.wikipedia.org/wiki/Floating_point)

Division by zero with floats does not crash (rather it gives that result you posted). Division by zero with ints does crash. By replacing the a and b with 1 you are making it integer division.

It's "fine" to divide by zero you just get that infinity value for the float. That's why with floats you generally want to check for zero before performing the division; otherwise you get bizarro values that ruin your simulations.

-me

##### Share on other sites
Yeah, that was pretty much it, Thanks!

##### Share on other sites
The problems with the + signs not appearing is limited to the Show Preview link

+, ++, +++, ++++, and so on do not appear in Show Preview

However they do appear in the forum

1. 1
2. 2
3. 3
Rutin
18
4. 4
5. 5
JoeJ
12

• 14
• 9
• 22
• 9
• 31
• ### Forum Statistics

• Total Topics
632618
• Total Posts
3007480
• ### Who's Online (See full list)

There are no registered users currently online

×