Loading your workspace…
Loading your workspace…
Read a number and demonstrate common functions from math.h: square root, power, ceiling, floor and absolute value.
#include <stdio.h>
#include <math.h>
int main(void) {
double x;
printf("Enter a number:\n");
if (scanf("%lf", &x) != 1) {
printf("Error: invalid input\n");
return 1;
}
printf("sqrt(x) = %.2f\n", sqrt(x));
printf("pow(x, 3) = %.2f\n", pow(x, 3));
printf("ceil(x) = %.2f\n", ceil(x));
printf("floor(x) = %.2f\n", floor(x));
printf("fabs(-x) = %.2f\n", fabs(-x));
return 0;
}
Input
2.4Output
Enter a number:
sqrt(x) = 1.55
pow(x, 3) = 13.82
ceil(x) = 3.00
floor(x) = 2.00
fabs(-x) = 2.40Input
0Output
Enter a number:
sqrt(x) = 0.00
pow(x, 3) = 0.00
ceil(x) = 0.00
floor(x) = 0.00
fabs(-x) = 0.00Each function in math.h works on doubles. The square root of a negative number is a domain error that returns NaN, so this demo uses a non-negative value to keep the output meaningful.
ceil rounds up and floor rounds down toward the nearest whole number, which is the difference you should be able to explain in the viva.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
2.4
Expected output
Enter a number: sqrt(x) = 1.55 pow(x, 3) = 13.82 ceil(x) = 3.00 floor(x) = 2.00 fabs(-x) = 2.40
0
Expected output
Enter a number: sqrt(x) = 0.00 pow(x, 3) = 0.00 ceil(x) = 0.00 floor(x) = 0.00 fabs(-x) = 0.00
math.h.
ceil rounds up to the next whole number, floor rounds down; for 2.4 they give 3 and 2.
It returns the absolute value of a floating-point number.
The maths functions live in a separate library that the linker must be told to include.
NaN, with a domain error, so negative input should be checked first.
Back to all RCU 21BCA1C1P lab programs.