Im having a problem with the while loop in my code, if I change what X2 is being compared to to anything other than 0 it doesnt hit the while loop, I am hoping its just some weird mistake. Thanks in advance for any help.

X2 = 0.5;

while (X2 >= 2.5)
{
            total = total + 1;
            X2 = X2 - 0.00001;
}

Recommended Answers

All 5 Replies

What's weird about 0.5 being less than 2.5? Is X2 a float?

What type of variable is X2, I guess it's probably an integer, which can't store floating numbers ...
Use a float instead ...

Member Avatar for stephen.id
#include <iostream>

using namespace std;

float X2 = 0.5;
int total;

int main() {
    cout << "Type The Number 0 To Loop: ";
    std::cin >> X2;
    if(X2 == 0.0f) {
        cout << "Looping....";
    }
    while (X2 == 0.0f)
    {
                total = total + 1;
                X2 = X2 - 0.00001f;
    }
return(0);
}

In that case it's actually very logic the while loop is never running: while (X2 == 0.0f) The syntax of a while statment: while([U]condition[/U]) So when condition is true the code in the loop is run, but since X2 has the value '0.5' and since 0.5 == 0.0 results in a false the loop is never run as a result ...

Fixed it, Thanks for the help guys.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.