I am finishing up some homework on for loops. I am stuck on a couple of the questions. I need to make this for loop output a number given for x - 0.5. x is given as an input by the user. Here is what I have for this:
1 2 3 4 5 6
double x;
cout << "Enter a value for 'x': " << endl;
cin >> x;
for (double x; x<=0.5; x++)
cout << x - 0.5 << endl;
Right now it does not output anything after the user inputs x.
My next question is how would I go about making a for loop that prompts the user for 10 integers and then it outputs the number of even and odd numbers? I think I could do this with a while loop easier but the assignment requires me to do it with a for loop.
Instead of using double x within the for loop, use a different name, ex: double a.
When you have it recall x, it will just erase the input from earlier in the code. This most likely causes nothing to be outputted cause x is most likely a random big number greater than 0.5.
The other thing x++ would increment by 1 and I'm not sure if you are purposely doing this or not. I most likely think you want to increment by 0.1. ex: x += 0.1.
So overall, your for loop should look like: for(double a = x; a <= 0.5; a += 0.5).
Or even yet, you could try this: for(x; x <= 0.5; x += 0.5).
The reason you need double n = something; is because it is unspecified what a POD stack variable will hold when not initialized. It could contain 0, or "garbage" data that was previous in memory.
1 2 3 4 5 6 7 8
double x;
std::cout << "Enter a value for 'x': " << std::endl;
std::cin >> x;
for(double n(0.); n<=0.5; x+=0.5)
{ // You forgot the { I suppose; or is the ending } part of another control structure?
std::cout << (x - 0.5) << std::endl;
}