Can't get simple math to work

I'm brand new at C++ and extremely clueless. I can't get a simple math function to print out the correct answer in cout.

The answer i'm looking for is 52/15 which = approximately 3.46666667
1
2
3
4
5
6
7
8
9
10
11
12
#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	float testnumber = 4*(1 - ( 1 / ((1*2+1)) ) + ( 1 / ((1*2+3))) );
	cout << testnumber << endl;
	cin.get();
	return 0;
}


It instead returns the integer 4.

All the values used in the calculation are of type int, so an integer divide will be done.
Example 22/7 will give 3 as the result.

If you want a floating point divide, make sure that at least one of the values is a floating point type
Example
22/7.0 7.0 is of type double
or
22.0f/7 22.0f is of type float


1
2
3
4
5
6
7
8
9
    cout.precision(14);

    double  testnumber = 4*(1 - ( 1.0 / ((1*2+1)) ) + ( 1.0 / ((1*2+3))) );
    cout << testnumber << endl;


    cout << 22/7    << endl;
    cout << 22/7.0  << endl;
    cout << 22.0f/7 << endl;
3.4666666666667
3
3.1428571428571
3.1428570747375


I would recommend the use of type double rather than float as a matter of routine, because of its higher precision.
Last edited on
Fixed your formula but it's not doing what you thought it should.
There is no reason to say 1* a number or 1\ a number but I left it in because you might have a reason.

This is what your actually doing.
// 4*(1-3+5)


1
2
3
4
5
6
7
8
int main ()
{

	float testnumber = 4*(1-((1*2+1)/1)+((1*2+3)/1));
	cout <<	4*(1-((1*2+1)/1)+((1*2+3)/1)) << endl;
	cout << testnumber << endl;
	return 0;
}
@SamuelAdams
Your "fixed" version doesn't give the required result of 3.46666667
Your right, don't know why /1.0 is not the same as 1.0/ but it's diff and I don't have time to look at it right now.
n/1 is how many 1s go into the number, which will return the number, n (for positive integers). 1/n will give how many times the number goes into 1. For positive integers larger than 1, this will yield the fraction 1 / n, which will always be smaller than n and smaller than 1. Big difference.

Why 52/15? lol
Last edited on
Topic archived. No new replies allowed.