函数参数有例外吗?
Are there exceptions for function arguments?
我正在尝试将参数输入到平方根函数中。该函数将接受值 b 乘以 b,但不接受值 b 乘以 b 减 4。这是为什么?我怎样才能解决这个问题?提前致谢。
#include <stdio.h>
//Function to compute square root of a number
float squareRoot (float x)
{
float guess = 1.0;
while (( x/ (guess * guess)) != 1)
{
guess = (x/ guess + guess) / 2.0;
}
return guess;
}
int main (void)
{
float b;
float valueOne;
float answerOne;
float squareRoot (float x);
printf("give me a 'b'\n");
scanf("%f", &b);
valueOne = b*b-4;
answerOne = squareRoot(valueOne);
printf("%f", answerOne);
return 0;
}
浮点相等性检查通常是不行的。而不是使用
( x/ (guess * guess)) != 1
替换为
( x/ (guess * guess)) >1.0000001 || ( x/ (guess * guess)) <=0.99999999
在大多数实际情况下,这会给你一个不错的精度。
我正在尝试将参数输入到平方根函数中。该函数将接受值 b 乘以 b,但不接受值 b 乘以 b 减 4。这是为什么?我怎样才能解决这个问题?提前致谢。
#include <stdio.h>
//Function to compute square root of a number
float squareRoot (float x)
{
float guess = 1.0;
while (( x/ (guess * guess)) != 1)
{
guess = (x/ guess + guess) / 2.0;
}
return guess;
}
int main (void)
{
float b;
float valueOne;
float answerOne;
float squareRoot (float x);
printf("give me a 'b'\n");
scanf("%f", &b);
valueOne = b*b-4;
answerOne = squareRoot(valueOne);
printf("%f", answerOne);
return 0;
}
浮点相等性检查通常是不行的。而不是使用
( x/ (guess * guess)) != 1
替换为
( x/ (guess * guess)) >1.0000001 || ( x/ (guess * guess)) <=0.99999999
在大多数实际情况下,这会给你一个不错的精度。