循环时,值k不会递增

时间:2014-02-18 01:45:15

标签: c loops while-loop

将值K设置为根据i递增,以便评估l1,l2,l3,l4直到k <= g。我做错了什么????

#include <stdio.h>
#include <math.h>

int main(void)  {

    float  c=0, h=0, x=0, i=0;

    printf("Proj. #2 - Juan Perez\n");
    printf("Power of lamps (in watts)?  ");
    scanf("%f" , &c);

    printf("Height of lamp (in meters)?  ");
    scanf("%f" , &h);

    printf("Distance apart? (in meters)?  ");
    scanf("%f" , &x);

    printf("Interval? (in meters)? ");
    scanf("%f" , &i);


    printf("Power: %f\n", c);
    printf("Height: %f\n",  h);
    printf("Distance apart: %f\n",  x);
    printf("Interval: %f\n",  i);

    float  k=75, d=0, e=x, f=2*x, g=3*x;
    float  l1=((c*h)/(powf((h*h)+((k-d)*(k-d)), 1.5)));
    float  l2=((c*h)/(powf((h*h)+((k-e)*(k-e)), 1.5)));
    float  l3=((c*h)/(powf((h*h)+((k-f)*(k-f)), 1.5)));
    float  l4=((c*h)/(powf((h*h)+((k-g)*(k-g)), 1.5)));
    float j=l1+l2+l3+l4;

    while (k<=g){
        printf("%f\n", j);
        k+=i;
    }

}

2 个答案:

答案 0 :(得分:2)

因为k = 75,并且g = 0,因为条件永远不会为真,所以该循环将永远不会执行,并且print语句将不起作用,并且k的增量也不会发生。

变化

while (k<=g){

while (k>=g){

观察它失控(在无限循环中运行),因为k总是大于g。

答案 1 :(得分:0)

我不建议使用浮点数递增while循环。

以下是指向原因的链接:Any risk of using float variables as loop counters and their fractional increment/decrement for non "==" conditions?

g也设置为零,永不更新。