问题描述:

So I'm wondering, how do I make sure that all steps in a loop are performed if the step size is smaller than 1? Take this loop for instance:

`for (float y, x = -1.0; x <= 1.0; x += 0.1) {`

y = (4*x*x*x) + (3*x*x) + (5*x) - 10;

printf("x = %.2f, y = %.2f\n", x, y);

}

Output:

`x = -1.00, y = -16.00`

x = -0.90, y = -14.99

x = -0.80, y = -14.13

x = -0.70, y = -13.40

x = -0.60, y = -12.78

x = -0.50, y = -12.25

x = -0.40, y = -11.78

x = -0.30, y = -11.34

x = -0.20, y = -10.91

x = -0.10, y = -10.47

x = 0.00, y = -10.00

x = 0.10, y = -9.47

x = 0.20, y = -8.85

x = 0.30, y = -8.12

x = 0.40, y = -7.26

x = 0.50, y = -6.25

x = 0.60, y = -5.06

x = 0.70, y = -3.66

x = 0.80, y = -2.03

x = 0.90, y = -0.15

I intend the loop to also run for x = 1, but as you can see it doesn't do that. I've heard that it's not safe to use floats as loop counters, as the float precision isn't exact. The fact that I'm using a float variable as the loop counter is probably the cause of my problem. So what solutions are there to my problem? Thanks in advance for your kind responses!

The problem, as you noted, is that you shouldn't use floats as loop counters. So multiply everything by 10 and use integers:

```
for (int x = -10; x <= 10; ++x) {
float y = (0.004*x*x*x) + (0.03*x*x) + (0.5*x) - 10;
printf("x = %.2f, y = %.2f\n", 0.1*x, y);
}
```

Produces:

```
x = -1.00, y = -16.00
x = -0.90, y = -14.99
x = -0.80, y = -14.13
...
x = 0.90, y = -0.15
x = 1.00, y = 2.00
```

as expected.

Perhaps even better: logically separate your loop variable from the meaningful stuff.

```
for(int i = -10; i <= 10; ++i) {
float x = 0.1 * i;
float y = (4*x*x*x) + (3*x*x) + (5*x) - 10;
printf("x = %.2f, y = %.2f\n", x, y);
}
```

您可能感兴趣的文章：

- r - Omitting certain lines of a .csv file with less no. of columns and reading the rest
- bash - Safely pass arguments to a command executed via su
- android - I upload a apps in google play ,its google map not work but when i run it lacal system to active device it work?
- ios - Method does not override any method from its superclass
- android - Invalid userID() when connecting TI SensorTag to IBM IoT Foundation via Bluemix
- php - Reading a specific line from a text file
- clr - Any implementation of an Unrolled Linked List in C#?
- Finding Hudson Log Files
- Forward to a payment-gateway together with POST data using cURL (or any other PHP server side solution)
- WCF in Winforms app - is it always single-threaded?

随机阅读：

**推荐内容**-

**热点内容**