计算帕斯卡的小数位数 [英] Counting the number of decimal places in pascal

查看:112
本文介绍了计算帕斯卡的小数位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Pascal,我必须做一个Pascal程序作为家庭作业。
我做到了,但我不知道如何计算实数中的小数位数(。后的位数)。

I just started studying pascal and I have to do a pascal program as homework. I made it but I don't know how to count the number of decimal places in a real number (the number of digit after the ".").

我只需要格式化一个实数即可(例如 write(real:0:dec)其中 dec 是我不知道如何知道的小数位数。我想这样做是因为我不希望它使用科学计数法或带有许多不必要的零。

I need it just to format well a real number (like write(real:0:dec) where dec is the number of decimal digit i don't know how to know). I'd like to do that because i don't want it in scientific notation or with many unnecessary zeros.

例如,如果实数为1.51(x)且我写了writeln(x:0:4);或WriteLn(Format(’%*。* f’,[0,4,x])));它会显示1.5100,但我希望它仅为1.51;如果数字是1.513436,则只会显示1.5134。所以我会让它像writeln(x:0:dec);

For example if a real number is 1.51 (x) and I write writeln(x:0:4); or WriteLn(Format('%*.*f', [0, 4, x])); it will show 1.5100 but I want it to be just 1.51; and if the number is like 1.513436, it will show only 1.5134 . So I would make it like writeln(x:0:dec); with something that makes dec the number of decimal digits of x.

推荐答案

Format()函数通常在这种情况下使用。

The Format() function is normally used in situations like this.

WriteLn(Format('%*.*f', [0, dec, your_real_number]));

*。* 被解释为 total_characters.decimal_digits 。第一个传递零表示根据实际大小调整宽度。小数位数可以是变量(十进制),您可以根据自己的要求进行调整。

*.* is interpreted as total_characters.decimal_digits. Passing zero for the first means that width is adjusted according to how large your real is. The number of decimals can be a variable (dec), which you can adjust to your specification.

更新:

您提到您想要一个精确的浮点数相对于小数位数的表示。

You mention that you want an exact representation of a float with respect to the number of decimals.

我的评论是,大多数浮点值没有有限的小数位数。多数小数部分不能用二进制类型表示。

As mentioned in my comment, most floating point values does not have a finite number of decimals. And most decimal fractions cannot be represented by a binary type.

有些库可以处理任意大小的浮点值。例如,请参见 TBigFloat 。有一个格式化例程可以从十进制浮点数中去除冗余零。

There are some libraries that can handle floating point values of arbitrary size. See TBigFloat for example. There is a formatting routine that can strip redundant zeroes from a decimal float.

仍然,可以使用通用格式说明符删除尾随零:

Still, there is a possibility to remove trailing zeroes by using the general format specifier:

WriteLn(Format('%g',[your_real_number]));

您还可以指定宽度和有效位数。

You can specify the width and the number of significant digits as well.

这篇关于计算帕斯卡的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆