Data type selection for mathematical calculation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main () {
double a,b,x,i,c,g,d,t;
	cin >> g;
	cin >> i;
	cin >> d;
	cin >> t;
	a = i/1000;
		if (t = 1)
			{
			b = 1 + a;
			c = pow(b,d);
			x = g + c;
			cout << "The result is: " << x << endl;
			}
		else if (t = 2)
				{
				b = 1 + a;
				c = b * d;
				x = g + c;
				cout << "The result is: " << x << endl;
				}
			else
				return(0)

I've tried different things but I can't seem to make it give a proper result. I'm assuming it's either the data type or something with the calculation. For example, if g=40000000, i=15, d=7 and t=1, the result is 4e+007 (x=4e+007), and if t=2, the result is the same. What data type should I declare?

Note: I've read that double stores integer and non-integer values. Is that completely true or is there something more to it?

Note2: I'm a total beginner and I started yesterday.
Last edited on
I've read that double stores integer and non-integer values. Is that completely true or is there something more to it?


A double contains 64 bits divided into two parts, a mantissa and an exponent. The mantissa is like a scientific notation part and the exponent is an exponent. This is different from an integer where a number is represented purely by a single binary value. Now, something to consider is that a number like 0.1 in decimal (base 10) is a repeating number in binary (0.0001100110011...). This means that there WILL be rounding errors.

In short, the following is NOT safe because it may not be EXACTLEY true due to potential rounding errors.
 
for (double i = 0; i != 1000000000; i+=0.1) something();

The for loop may not exit because i may not be EXACTLEY 1000000000.


Now for your other issue:
For any numbers representing a real value, doubles are perfectly reasonable. Use integers for increments or numbers that WILL NOT have a remainder. So double is okay. Note that the 64 bits that make a double do not contain any operation on formatting. The cout itself is what controls that. If you want to see 40000000 instead of 4e+007, then you'll need to use iomanipulators.

cout << "The result is: " << fixed << x << endl;
The "fixed" manipulator forces non-scientific notation.

One further issue: Lines 12 and 19 should be
if (t==1) not [if (t=1)
Last edited on
Wow, this cleared up a lot. Thanks.

About the remark on the bottom of your post. I forgot to edit this post here. I know there has to be a double equal sign. It just didn't make any difference because the code was broken.
Topic archived. No new replies allowed.