溫馨提示×

c語言程序sqrt函數(shù)能處理負(fù)數(shù)嗎

小樊
81
2024-10-18 06:15:15
欄目: 編程語言

在C語言中,sqrt 函數(shù)來自 <math.h> 庫,它用于計(jì)算一個(gè)非負(fù)數(shù)的平方根。如果你嘗試對一個(gè)負(fù)數(shù)調(diào)用 sqrt 函數(shù),它會返回一個(gè) NaN(Not a Number),這是一個(gè)特殊的浮點(diǎn)數(shù)值,表示未定義或不可表示的結(jié)果。

例如:

#include <stdio.h>
#include <math.h>

int main() {
    double num = -4;
    double result = sqrt(num);
    if (isnan(result)) {
        printf("The square root of a negative number is NaN.\n");
    } else {
        printf("The square root is %f.\n", result);
    }
    return 0;
}

這段代碼會輸出 “The square root of a negative number is NaN.”,因?yàn)?-4 的平方根是未定義的。

如果你需要處理負(fù)數(shù),你可能需要自己實(shí)現(xiàn)一個(gè)平方根函數(shù),或者使用其他方法來處理負(fù)數(shù)的平方根情況(例如,返回一個(gè)錯(cuò)誤碼或特殊值)。

0