【发布时间】: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
【问题讨论】:
-
您是否尝试过在调试器中逐行执行代码?也许您应该花点时间阅读 Eric Lippert 的 How to debug small programs,并学习如何使用调试器。
-
但它不是这样工作的 那么,它是通过什么方式工作的?
-
乘数是什么?
-
很可能
45.123*1000不完全等于45123。