【问题标题】:0.1 increment in a While Loop (C Programming)While 循环中的 0.1 增量(C 编程)
【发布时间】:2015-02-12 23:28:14
【问题描述】:

我正在上 C 编程入门课程。我们最新的项目让我们编写代码以使用 while 循环以 0.1 步长将 1-10 的 xsqrt(x) 值制成表格。但是,当我尝试进行 0.1 增量时,没有任何内容添加到起始整数 1 中,并且程序在无限循环中运行。我将在下面发布代码。除了不执行该步骤之外,程序运行良好(并且可以使用其他增量,例如 1 等)。我该如何解决这个问题?

#include <stdio.h>
#include <math.h>
int main(void)
{
   int x=1;
   double sq_rt;
   printf("Square Root Table: \n");
printf("Value of X        Square Root of X\n");    
while (x <= 10)
   {
      sq_rt = sqrt (x);     
printf("%6i %20f \n", x, sq_rt);   
x += 1e-1;
  }
   return 0;
}

【问题讨论】:

  • 您不能将 0.1(浮点数)添加到整数 (x);将x 声明为浮点数:double x = 1;
  • 是的,你可以。它并不总是如你所愿。
  • @MartinTörnwall 是的,但我认为对于这个问题,将其保持为“不,你不能。”更有意义。最好作为一个完整的答案来解释这里发生的事情。
  • 那我应该怎么写呢?就像现在一样,它在无限循环中运行,一直取 1 的平方根
  • @Evert:我不同意。当它清楚地编译没有错误时说“不,你不能”可能会比解释它是合法的但没有达到预期的效果更容易造成混乱。

标签: c while-loop increment tabular


【解决方案1】:

int 类型只允许您存储整数(即 -2、-1、0、1、2 等)。要存储带小数点的数字,您需要双精度(或double)类型。将main()的第一行改为:

double x = 1.0;

如果您尝试将1e-1 添加到int,它将首先将其转换为int - x 的类型 - 当被截断时最终将为零,所以你永远不会真正向x 添加任何内容。

【讨论】:

  • s/舍入/截断 ;)
  • 1.0 开头并重复添加1.0 很可能由于舍入错误而无法达到10.0。 (也许这就是练习的重点?)
  • @Keith Thompson 怀疑您的意思是“在评论中添加 0.1”。
  • @chux:是的。也许我使用的是小端符号。 8-)}
【解决方案2】:

程序中的行

x += 1e-1;

正在执行相当于

的操作
x = (int)(((double)x) + 0.1);

换句话说,x首先被转换为double,然后加上0.1,得到1.1。然后将该值转换为int,得到值1,分配给x。

解决方法是将x 的类型更改为浮点类型,例如floatdouble

分享和享受。

【讨论】:

    【解决方案3】:

    以下代码是关于如何执行所需算法的建议。

    #include <stdio.h>
    #include <math.h>
    
    // define the magic numbers, don't embed them in the code
    #define UPPER_LIMIT (10.0)
    #define STEP_SIZE   (0.1)
    
    int main(void)
    {
        double x=1.0;
        double sq_rt;
    
        printf("Square Root Table: \n");
        printf("Value of X        Square Root of X\n");
    
        // due to ambiguities in 'real' values, 
        // this loop will iterate approx. 90 times.
        while( x < UPPER_LIMIT )
        {
            sq_rt = sqrt (x);
    
            // display the two double values
            // note: long float conversion values 
            // because the underlying numbers are double
            // note: blanks for alignment with column headers
    
            printf("%9.6lf        %16.13lf \n", x, sq_rt);
    
            // increase base value by increment of 0.1
            x += STEP_SIZE;
        } // end while
    
       return 0;
    } // end function: main
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-21
      • 2011-11-07
      • 2018-06-26
      • 2016-04-22
      • 2016-08-05
      • 2015-10-10
      • 2015-02-12
      相关资源
      最近更新 更多