Tính căn bậc hai của một số

Viết chương trình cho phép người dùng nhập số bất kỳ tên n rồi tính căn bậc hai của số đã nhập. Trước khi tính căn bậc hai, chương trình cần kiểm tra xem số đầu vào có âm hay không.
nguyenthanhtruong avatar
nguyenthanhtruong
c_cpp
01/16/2024 8:27 AM
1.2 KB
29
Indexable
//Write a program that allows user to enter any number named n and then calculates square root
//of the number entered. Before calculating the square root, the program needs to check whether
//the input number is negative or not.
//Hint: use the function double sqrt (double n) of the math.h library to calculate the square root of
//the parameter n.
//Example 1: Please enter any number: -2
//Accept positive number only!
//Example 2: Please enter any number: 15
//Square root of 15.000000 is 3.872983
//Example 3: Please enter any number: 0
//Square root of 0.000000 is 0.000000

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

int main() {
    double n;
    printf("Please enter any number: ");
    scanf("%lf", &n);
    if (n < 0) {
        printf("Accept positive number only!\n");
    } else {
        double squareRoot = sqrt(n);
        printf("Square root of %.6lf is %.6lf\n", n, squareRoot);
    }

    return 0;
}
Editor is loading...
Leave a Comment