user2087867
user2087867

Reputation: 105

I have an issue printing out an array

I cant figure out why this wont print out correctly.

void countChars(ifstream& inData, string filename, int x[], int y[])
{
    char ch;
    int count = 0;

    for(int i=0; i < 58; i++)
    {
        x[i] = 0;
}
    inData.open(filename.c_str());

    while (inData >> ch)
    {
        count++;
        if ((ch >= '!') && (ch <= 'Z'))
        {
            x[ch - '!']++;
        }
    }

    for(int i=0; i < 58; i++)
    {
        y[i] = (x[i] / count * 100);
        cout << y[i] << endl;
    }   
}

It should print out the % of the file each character makes up. What it does print out is 58 0s. I don't understand exactly why it doesn't print out right, I reread the chapters on arrays and couldn't find anything about this type of problem. I tried to search first but I'm not even sure what terms I should be searching for with this problem.

Upvotes: 0

Views: 95

Answers (4)

bvj
bvj

Reputation: 3392

y[i] = (int)(x[i] * 100.0 / count + 0.5);

Upvotes: 1

Jain
Jain

Reputation: 984

change data types of either of the x or count to float or double.

Upvotes: 1

Glandy
Glandy

Reputation: 91

Well obviously in your line

y[i] = x[i] / count * 100

every field in your x-Array is probably smaller than count thus the result of your division is always below 1, since you chose to use integers that's always 0 and 0 * 100 = still 0.

Upvotes: 1

Aswin Murugesh
Aswin Murugesh

Reputation: 11080

The arrays x,y and count are integer arrays. So as x[i] < count always, the division value is always 0. so change x, y, count as double..

Upvotes: 1

Related Questions