【问题标题】:While loop, value k will not incrementWhile循环,值k不会增加
【发布时间】:2014-02-18 01:45:15
【问题描述】:

值 K 设置为根据 i 递增,以便评估 l1、l2、l3、l4 直到 k

#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;
    }

}

【问题讨论】:

  • 你说“直到 k

标签: c loops while-loop


【解决方案1】:

由于k = 75,g = 0,因为条件永远不成立,所以循环永远不会执行,print语句也不会工作,k的增量也永远不会发生。

改变

while (k<=g){

while (k>=g){

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

【讨论】:

  • FWIW,g 在循环之前设置为 3*x,但除非 x 大于 25,否则同样的原则适用。
  • g 是 x 输入的 3 倍。我的意思是从 0 开始更改 k。
【解决方案2】:

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

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

g 也设置为零并且从不更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    相关资源
    最近更新 更多