gpt-4-1106-preview· openai
Suzhen/CodeChat
c program to fi d square root
- User
c program to fi d square root
- Assistant
Here's an example of a simple C program that calculates the square root of a number using the
sqrtfunction provided by themath.hlibrary:#include <stdio.h> #include <math.h> int main() { double number, squareRoot; printf("Enter a number to find the square root: "); scanf("%lf", &number); // Check if the number is negative if (number < 0) { printf("Sorry, square root of a negative number is imaginary.\n"); return 1; } squareRoot = sqrt(number); printf("The square root of %.2f is %.2f\n", number, squareRoot); return 0; }To compile and run this program, save it to a file with a
.cextension (for example,sqrt_example.c), and then use a C compiler likegcc:gcc sqrt_example.c -lm -o sqrt_example ./sqrt_exampleThe
-lmflag tells the compiler to link against the math library, where thesqrtfunction is defined.Note: Always remember to perform proper checks and validation as needed, such as in cases where you expect valid numeric input from the user. This example does basic checking for a negative number.