#include <stdio.h>
unsigned int square_root_fun(unsigned int value, unsigned int *after_dec_point_ptr)
{
unsigned int max_num, i, root;
if (value <= 1)
{
if (after_dec_point_ptr != NULL)
*after_dec_point_ptr = 0;
return value;
}
value *= 10000; // Magnification 10000 times
for (max_num = 31; max_num > 0; max_num--)
{
if (value & (1 << max_num))
break;
}
root = 0;
for (i = (max_num >> 1); i > 0; i--)
{
if (value >= ((root | (1 << i)) * (root | (1 << i))))
root |= (1 << i);
}
if (i == 0)
{
if (value >= ((root | (1 << i)) * (root | (1 << i))))
root |= (1 << i);
}
if (after_dec_point_ptr != NULL)
{
*after_dec_point_ptr = root % 100; // Restore magnification and Storage position after decimal point
}
root /= 100; // Restore magnification
return root;
}
int main()
{
unsigned int var_a, root, after_dec_point_ptr;
printf("\nPlease input a value:");
scanf("%d", &var_a);
printf("\n=============================================\n");
root = square_root_fun(var_a, &after_dec_point_ptr);
printf("%d square root is %d.%d", var_a, root, after_dec_point_ptr);
printf("\n=============================================\n");
return 0;
}
Please input a value:123456
=============================================
123456 square root is 351.36
=============================================
Please input a value:2345
=============================================
2345 square root is 48.42
=============================================
Please input a value:1
=============================================
1 square root is 1.0
=============================================
Please input a value:0
=============================================
0 square root is 0.0
=============================================
沒有留言:
張貼留言