【发布时间】:2020-02-20 10:42:58
【问题描述】:
我想逐位读取 C 中 5 的 sqrt 的小数。 5 的平方根是 2,23606797749979...,所以这是预期的输出:
2
3
6
0
6
7
9
7
7
...
我找到了the following code:
#include<stdio.h>
void main()
{
int number;
float temp, sqrt;
printf("Provide the number: \n");
scanf("%d", &number);
// store the half of the given number e.g from 256 => 128
sqrt = number / 2;
temp = 0;
// Iterate until sqrt is different of temp, that is updated on the loop
while(sqrt != temp){
// initially 0, is updated with the initial value of 128
// (on second iteration = 65)
// and so on
temp = sqrt;
// Then, replace values (256 / 128 + 128 ) / 2 = 65
// (on second iteration 34.46923076923077)
// and so on
sqrt = ( number/temp + temp) / 2;
}
printf("The square root of '%d' is '%f'", number, sqrt);
}
但是这种方法将结果存储在一个浮点变量中,我不想依赖浮点类型的限制,例如我想提取 10,000 位数字。我还尝试使用本机 sqrt() 函数并使用 this method 将其转换为字符串编号,但我遇到了同样的问题。
【问题讨论】:
-
你有两种选择:1)将数字转换为字符串,将字符串中的每个字符一个一个打印出来;或者 2) 使用十进制算术一个一个地得到每个数字(整数截断和与
10的乘法就是你所需要的)。 -
在您的问题中,您声明您想逐位“读取”
sqrt(5),但在我看来,您真的想编写一个程序来“计算”这个数字,然后按数字打印按数字。请注意,计算机通常可以使用固定数量的有效数字,并且您需要一个特殊的库才能根据需要使用尽可能多的小数位 - 正如@pmg 所指出的那样。 -- 计算机通常固定为一组数字以节省内存,或者至少使其易于管理,以便计算机知道为每个数字分配多少内存...... -
您的方法近似平方根,直到达到浮点的最大精度,即。直到
sqrt不再改变。要获得更高的精度,您将需要另一种方法。 -
不可能无限期地使用有限位数来计算 sqrt(5) 的位数进行计算,因为有限位数只有有限数量的状态,所以行为必须开始重复在某些时候,因此必须产生一个重复的十进制数字。重复的十进制数字是有理数,但 sqrt(5) 是无理数。因此,一个“永远”打印 sqrt(5) 数字的程序必须使用任意精度的算法,随着时间的推移使用越来越多的内存(这意味着它也必须在有限的世界中耗尽它的能力)。
标签: c math casting floating-point sqrt