【问题标题】:Why is return not working in this code? [duplicate]为什么 return 在此代码中不起作用? [复制]
【发布时间】:2018-03-21 19:46:34
【问题描述】:

我用 C 语言创建了一个代码,用于查找长双精度数小数点后的总位数,这就是代码 -

#include <stdio.h>
int main(void)
{
    long double number,temp; int num,count=0;
    printf("\nEnter a number=");
    scanf("%Lf",&number);
    printf("\nEnter multiplication factor=");
    scanf("%d",&num);
    if(num>10)
    {
        printf("\nPlease enter a multiplicative factor <10");
        return 1;
    }
    if(number>0)
    {
       for(int i=0;i<num;i++)
       {
        number=number*10;
        temp=number-(int)number;
        printf("\ntemp=%Lf\n",temp);
        if(temp!=0)
        {
        count=count+1;
        }
        else
        {   
            return 1;
        }
       }
       printf("\nTotal number of decimal points=%d",++count);

    }
    else if (number<0)
    {
        number=(-1)*number;
        for(int i=0;i<num;i++)
       {
        number=number*10;
        temp=number-(int)number;
        printf("\ntemp=%Lf\n",temp);
        if(temp!=0)
        {
        count=count+1;
        }
        else
        {   
            return 1;
        }
       }
       printf("\nTotal number of decimal points=%d",++count);
    }
    else
    {
        printf("\nNumber has no decimal points\n");
    }
}

我在哪里使用了示例可以理解的逻辑 -
如果数字=45.123
倍增因子=5
然后数字=45.123*10=451.23 和温度= 451.23-451=0.23
=451.23*10=4512.3 和温度= 4512.3-4512=0.3
=4512.3*10=45123 和温度= 45123.0-45123=0.0

这是程序应该终止的地方,因为我使用了 return 1,但它不是以这种方式工作的,因为程序将数字乘以 10,因为它使用了乘法因子的次数。

这里是输出 -

aalpanigrahi@aalpanigrahi-HP-Pavilion-g4-Notebook-PC:~/Desktop/Daily programs$ ./decimal

Enter a number=45.123

Enter multiplication factor=5

temp=0.230000

temp=0.300000

temp=0.000000

temp=0.000000

temp=0.000000

Total number of decimal points=6 

【问题讨论】:

  • 最好将\n 放在printf 格式字符串的末尾(或使用fflush)。编译所有警告和调试信息:gcc -Wall -Wextra -gGCC。然后使用调试器 gdb。尝试在您的问题中找到一些MCVEfix-my-code 问题与 SO 无关
  • 您是否尝试过在调试器中逐行执行代码?也许您应该花点时间阅读 Eric Lippert 的 How to debug small programs,并学习如何使用调试器。
  • 但它不是这样工作的 那么,它是通过什么方式工作的?
  • 乘数是什么?
  • 很可能45.123*1000 不完全等于45123

标签: c for-loop return


【解决方案1】:

抱歉,我一开始误解了您的代码。 问题是您正在使用 != 将浮点数与 int 进行比较。你永远不应该这样做。尝试与

进行比较
if(temp!=0.0f)

与一个非常小的数字进行比较会更好:

if (temp<0.00000001f)

像这样:

if(number>0)
{
   for(int i=0;i<num;i++)
   {
      number=number*10;
      temp=number-(int)number;
      printf("\ntemp=%Lf\n",temp);
      if(temp<0.0000001f)
      {
         count=count+1;
      }
      else
      {   
         return 1;
      }
  }
  printf("\nTotal number of decimal points=%d",++count);

}

【讨论】:

  • 即使删除了该语句,它也无法正常工作。
  • 您不应删除该语句,而应添加“return 1”。在 printf 之后。然后一旦数字为0就会停止并打印正确的数字。
  • 输出根本不包含这一行。
  • “您正在将浮点数与 int 进行比较……”这不是问题所在。实际上,OP 确实比较浮点数。阅读通常的算术转换。而且使用魔法值也不好。使用标准常量。
  • 与 0 的比较仍然会导致比 t 解决的问题更多...
猜你喜欢
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多