Darkaura
Darkaura

Reputation: 11

My variables will not take any value

Hello I am having trouble with this variable Total_vot I do not know why but the value that i want the total votes from vote[i] to add up and that value will become Total_vot. But it it says that the variable is uninitialized which means that i didn't put a zero at the time i created the variable. I want the value to be all the added up votes. but it doesn't work why?

I'm a slight beginner so please be kind :)

int Total_vot;

    double *POV = new double[ppl];  
    cout << "this is the percentage of votes each candidate got!" << endl;

    for (int i = 0; i < ppl; i++)
    { 
        Total_vot  += vote[i];
    } 
    cout << Total_vot << endl;
    for (int i = 0; i < ppl; i++)
    {
        POV[i] = vote[i] / Total_vot * 100;
    }
    for (int i = 0; i < ppl; i++)
    {

        cout << cans[i]; cout << "     " << vote[i]; cout << "     " << POV[i]; cout<<"%" << endl << endl;

Upvotes: 0

Views: 54

Answers (1)

Barmar
Barmar

Reputation: 781255

First, you need to initialize Total_vot:

int Total_vot = 0;

That will get rid of the warning about the uninitialized variable, and the total will be correct.

Second, the assignment

POV[i] = vote[i] / Total_vot * 100;

is performing integer arithmetic because all the operands are integers. When it divides vote[i] by Total_vot this will be a fraction, and will be rounded down to 0. It doesn't matter that you're assigning to a double; first it calculates the result of the expression, then it converts that result to double for the assignment.

You need to cast at least one of the operands to double before doing the division:

POV[i] = vote[i] / (double) Total_vot * 100;

Upvotes: 4

Related Questions