Skip to main content
GameDev.net gamedev.net
🔒 Locked

Division by zero (C++)

Started by algumacoisaqualquer May 14, 2007 at 6:53 PM 2 replies 8k views
Original Post
algumacoisaqualquer
algumacoisaqualquer
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?
Palidine
Palidine
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
Adam Hamilton
Adam Hamilton
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.