Basic Math coding

I am new to C++, self-teaching myself, I am trying to get a simple calculation to work but it isn't doing what I set up. . .am I missing something??
_______________________________________
#include <iostream>
#include <iomanip>

using namespace std;
int main ();
{
int a,b;

cout<<"Number of people who like Sprite: ";
cin>>a;
cout<<"Number of people who like Pepsi: ";
cin>>b;

int e;
e=a+b;
float c,d;
c=a/e*100;
d=b/e*100;

cout<<setprecision(4)<<fixed<<c<<" percent of people like Sprite \n";
cout<<setprecision(4)<<fixed<<d<<" percent of people like Pepsi \n";
cout<<"\n"
cout<<e<<" people like both ";

return 0;

}
_________________________________________________

I can't get the percentage to work, the display shows the desired decimal places but no proper calculation happens, the sum calculation works ok;

Any ideas?? Remember be gentle I am new. . .:)

Oops I typed the previous one in wrong, the int and float got transposed. . .sorry guys. .
Last edited on
In your lines of code:
1
2
c = a/e * 100;
d = b/e * 100;


a, b, and e are all integers. C and C++ perform integer division when both the divisor and dividend are integers and floating point division when at least one of the two is floating point.

In order to fix your problem, you need to force either your divisor or dividend to be floating point before performing the division. One way to do this (this is the simplest, but not the best):

1
2
c = a / (float)e * 100;
d = b / (float)e * 100;


This coerces ("typecasts" as it is called in C++-speak) e to be floating point before
the division occurs so that floating point division is used instead of integer division.

Thanks soo much. . .using your advice I played around and finally redesignated 'e' as a float and it compiled and ran beautifully.

Now I understand a heck of a lot better about forcing mixes in mixed operations.

Once again much thanks. . .:)

Topic archived. No new replies allowed.