Help Dividing in C++

I need help with why my code won't display the right solution to the division I coded on line 25-28
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

int main()
{
int males, females, total, mpercentage, fpercentage;

cout << "How many males are in the class?";
cin >> males;
cout << "How many females are in the class?";
cin >> females;

total = males + females;
cout << "The total students are " << total << endl;

cout << fixed << setprecision(2) << total;
mpercentage = males / (males + females) * 100;
cout << mpercentage << "%" << " of the class are males \n";
fpercentage = females / (males + females) * 100;
cout << fpercentage << "%" << " of the class are females \n";
Hello LyonPredator,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

Please post the whole program. You appear to be missing the "return 0;" and closing } to main. It makes me wonder if there is anything else missing.

First off you are using ints for your division which looses the decimal portion of the division. So when numbers are rounded to fit into an int you will receive the wrong answer.

I believe it is line 8 would work better as:
double males{}, females{}, total{}, mpercentage{}, fpercentage{};
The empty {}s will initial each variable to "0.0". You should always initialize your variables when they are defined else you could use one of those variables before you give it a value and the resulting garbage in the variable would give you unwanted results.

I have not run your program to check the math yet, so I think it might work. Changing the variables form ints to doubles will be a big improvement.

Hope that helps,

Andy
Last edited on
Topic archived. No new replies allowed.