【问题标题】:Are there exceptions for function arguments?函数参数有例外吗?
【发布时间】:2021-04-21 00:33:39
【问题描述】:

我正在尝试将参数输入到平方根函数中。该函数将接受 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;
 }

【问题讨论】:

    标签: c function arguments


    【解决方案1】:

    浮点相等检查通常是不可行的。而不是使用

    ( x/ (guess * guess)) != 1

    替换为

    ( x/ (guess * guess)) &gt;1.0000001 || ( x/ (guess * guess)) &lt;=0.99999999

    这将在大多数实际情况下为您提供良好的精度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      相关资源
      最近更新 更多