Home > Net >  for loop not taking any floating point variables
for loop not taking any floating point variables

Time:06-12

I have this problem, where I can input "2 10 8" and it will output "8", but I want to be able to input "2 -25.2 -38.4". This immediately crashes the for loop and the program displays "-25.0" instead of "-25.2", effectively deleting the number in the decimal place.

Is there anyone that can help?

int main() {
    int numVals;

    static_cast<double>(numVals);
    double minVal;
    int i;
    int iteration;
    cin >> iteration;

    for (i = 0; i < iteration;   i) {
        cin >> numVals;
        numVals = numVals * 10; //program completely ignores this...
        if (i == 0) {
            minVal = numVals;
        }
        else if (numVals < minVal) {
            minVal = numVals;
        }
    }

    cout << fixed << setprecision(1)  << minVal / 10 << endl;

    return 0;
} 

CodePudding user response:

You are trying to read -25.2 to a numVals variable of type int. It reads -25 to numVals, but then tries to read .2 next time, which is not a valid integer. When you tried this, the input stream variable cin goes to a failure state, and doesn't take any more input.

Change numVals from type int to double:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    double numVals;
    double minVal;
    int i;
    int iteration;

    cin >> iteration;

    for (i = 0; i < iteration;   i)
    {
        cin >> numVals;
        numVals = numVals * 10;
        if (i == 0)
        {
            minVal = numVals;
        }
        else if (numVals < minVal)
        {
            minVal = numVals;
        }
    }

    cout << fixed << setprecision(1) << minVal / 10 << endl;

    return 0;
}
  • Related