将c中的0和0.0区分为while循环的中断条件

时间:2015-12-21 19:29:35

标签: c while-loop scanf precision break

我试图打破我的while循环。 如果插入字符“0”,我的程序应该打破循环。 但是,如果插入了字符'0.0',程序不应该中断循环并继续工作。我已经尝试过不同的解决方案(getchar,获取),但没有成功。 有任何想法吗 ?

while(1)
{
    double x[1000];
    scanf("%lf", &x[i]);

    if(x[i]=0 && x[i]!=0.0)
        break;

    i++;
}

3 个答案:

答案 0 :(得分:2)

if(x[i]=0 && x[i]!=0.0)

x[i]=0分配(不比较)

为了区分00.0,您需要比较一个字符串(而不是double

scanf("%s", str);
if (str[0] == '0' && strchr(str, '.') == NULL) {
    /* 0 */
}

然后,您可以转换为double

x[i] = strtod(str, NULL);

答案 1 :(得分:2)

x[i]的类型为double,0在比较时会转换为double。因此,无论您使用0.0还是0,都没有区别。在IEEE-754中,0表示为所有位0.因此,它在比较中没有区别。您无法将00.0区分开来。我真的不明白为什么你有这样一个循环条件让你明显地对待它们。

话虽如此,您可以使用fgets()作为字符串进行阅读,并将其与0进行比较。如果没有,请使用strtod()将其转换为double

while(1)
{
    double x[1000];
    char buf[256];
    char *p;

    fgets(buf, sizeof buf, stdin);    
    p = strchr(buf, '\n');
    if(p) *p = 0;  // Remove the trailing newline, if present
    if (strcmp(buf, "0") == 0) break;

    x[i] = strtod(buf, 0);   

    i++;
}

为了简洁,省略了错误检查。在实际代码中,您应该检查失败fgets()strtod()

答案 2 :(得分:0)

转换为double()的文字不会保留其原始文字形式。

将测试作为字符串读取并测试结束条件

#define N 1000
#define BUFN 80
double x[N];
for (i=0; i<N; i++) {
  char buf[BUFN];
  if (fgets(buf, sizeof buf, stdin) == NULL) break;

  // Scan for end pattern: (optional white-space) 0 (optional white-space)
  int n = 0;
  sscanf(" 0 %n", &n);  // n is set when pattern is matched
  if (n > 0) break;

  // error checking omitted for brevity
  double x[i] = strtod(buf, 0);
}