Hello, I have been having a problem with the following code:

#include<iostream>
#include<time.h>
#include<iomanip>
using namespace std;
int main()
{
        float average;
	setprecision(5);
	fixed;
	average = 100-((25/(130-(50-(130/3))))*100);
	cout << average << "\n\n";
}

I cannot seem to get the 'average' variable to come out to exactly 79.73 like it should. I have tested out the 'setprecision/fixed' functions, yet the program still produces 100.

Any help is appreciated.

Recommended Answers

All 2 Replies

Thats because you are doing int arithmatic. Basically :

130/3 = 43
130.0/3.0 = 43.333333...

So to solve your problem, and to be safe, put a .0 at the end of each numbers. So in total it will look like this :

average = float(100.0-((25.0/(130.0-(50.0-(130.0/3.0))))*100.0) );

The float(...) is a cast so the compiler does not give warnings.
Alternatively, you could put a .0f at the end of each number and not do the cast.

Thats because you are doing int arithmatic. Basically :

130/3 = 43
130.0/3.0 = 43.333333...

So to solve your problem, and to be safe, put a .0 at the end of each numbers. So in total it will look like this :

average = float(100.0-((25.0/(130.0-(50.0-(130.0/3.0))))*100.0) );

The float(...) is a cast so the compiler does not give warnings.
Alternatively, you could put a .0f at the end of each number and not do the cast.

Ah, okay. Thanks. That helped a lot. =]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.