Wan
Wan

Reputation: 13

Decimal point not displaying

I intend to let user key in positive integer value only but I realized that the output is wrong. For example largest value I entered is 100.6, the largest value displayed is only 100. I believe the problems come from atoi. Can anyone look at my code and tell me whats wrong?

    #include<iostream>
    #include<string>
    using namespace std;

    int main()
    {
    const int SIZE = 12;
    string month[SIZE] = { "Jan", "Feb", "Mar","April","May","June","July","August","Sept","October","Nov","Dec"};
    string highestMonth, lowestMonth;
    char temp[SIZE]; 
    double rainFall[SIZE], total = 0.0, average, highest, lowest;
    bool flag;
    int i = 0;

    do{
        flag = false;
        cout << "Enter rainfall for " << month[i] << " : ";
        cin >> temp;
        for (int j = 0; j < strlen(temp); j++)
        {

            if (!isdigit(temp[j]))
            {
                if (temp[j] == '.')
                    continue;
                cout << "Enter positive integer value only" << endl;
                flag = true;
                break;
            }

        }



        if (flag == false)
        {
            rainFall[i] = atoi(temp);
            total += rainFall[i];
            i++;
        }
    } while (i < SIZE);

    average = total / 12.0;

    lowest = rainFall[0];
    lowestMonth = rainFall[0];

    for (int i = 1; i < SIZE; i++)
    {
        if (rainFall[i] < lowest)
            lowest = rainFall[i];
        lowestMonth = rainFall[i];
    }

    highest = rainFall[0];
    highestMonth = rainFall[0];
    for (int i = 1; i < SIZE; i++)
    {
        if (rainFall[i]>highest)
            highest = rainFall[i];
        highestMonth = rainFall[i];
    }

    cout << "Total rainfall:" << total << endl;
    cout << "Average:" << average << endl;
    cout << "Highest:" << highest << " in " << highestMonth << endl;
    cout << "Lowest:" << lowest << " in " << lowestMonth << endl;

    system("pause");
    return 0;
}

Upvotes: 0

Views: 41

Answers (2)

David Schwartz
David Schwartz

Reputation: 182761

You set flag to true if the input has a decimal point and you have no code to process the decimal input whatsoever.

    if (flag == false)
    {
        rainFall[i] = atoi(temp);
        total += rainFall[i];
        i++;
    }

This code processes the input if flag is false, but there's no analogous code to handle decimals if flag is true.

Upvotes: 1

Lucacox
Lucacox

Reputation: 317

atoi convert string representation of a number into an integer so "100.6" is converted into 100.

You can use atof

Upvotes: 2

Related Questions