Question

Code in question:

        std::stringstream cd;
        int f = int((15 / allyCounter) * 100);
        cd << f;

allyCounter is equal to 45. the idea is to get what percentage 15 is of allyCounter where allyCounter is a dynamic int that is constantly changing. i don't have much experience with c++ so I'm sure what I'm missing is something fundamental.

Was it helpful?

Solution

The problem here is almost certainly with integer vs. floating point math.

15/45 (when done in integer math) is 0.

Try

    std::stringstream cd;
    int f = int((15.0 / allyCounter) * 100);
    cd << f;

...and see if things aren't better. 15.0 is a double precision floating point constant, so that'll force the math to be done in floating point instead of integers, so you'll get a percentage.

Another possibility would be to do the multiplication ahead of the division:

int f = 1500 / allyCounter;

If the numerator were a variable, this could lead to a problem from the numerator overflowing, but in this case we know it's a value that can't overflow.

OTHER TIPS

In C++, 15 / 45 is 0. (It's called "integer division": the result of dividing two ints in C++ is also an int, and thus the real answer is truncated, and 15 / 45 is 0.)

If this is your issue, just make it a double before doing the division:

int f = static_cast<double>(15) / allyCounter * 100;

or even:

int f = 15. / allyCounter * 100;

(The . in 15. causes that to be a double.)

You are using integer division:

std::stringstream cd;
int f = int((15.0 / allyCounter) * 100);
cd << f;

The compiler sees 15/allyCounter and thinks it should return an integer (you passed it two integers, right?). 15/150 == 0 with integer division, you always round down. In this case the compiler sees 15.0 as a double, and uses decimal places.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top