Then we changed types of the variables: instead of int we made them double and changed the format specifiers correspondingly: from %d to %lf. The result of division 8/3 in the last line has changed: it was 2 for int and it became 2.666666 for double.
We also checked what happens if a variable of type double was printed with format specifier %d (as though it was an integer), see printf("After z=2*x-y... The result didn't look meaningful.
/*******************************
File lab3.c
M2120-Fall'05-Lab 3- Thursday
Author: Sergey Sadov
Date: Thursday Sept.22 2005
Program from Wed Sept 21 Lecture
********************************/
#include <stdio.h>
int main()
{
double x;
double y;
double z;
printf("Before initialization: x=%lf, y=%lf, z=%lf\n",x,y,z);
x=2;
printf("After x=2: x=%lf, y=%lf, z=%lf\n",x,y,z);
y=5;
printf("After y=5: x=%lf, y=%lf, z=%lf\n",x,y,z);
x=x+5;
printf("After x=x+5: x=%lf, y=%lf, z=%lf\n",x,y,z);
y++;
printf("After y++: x=%lf, y=%lf, z=%lf\n",x,y,z);
z=2*x-y;
printf("After z=2*x-y: x=%d, y=%d, z=%d\n",x,y,z);
y/=2;
printf("After y/=2: x=%lf, y=%lf, z=%lf\n",x,y,z);
z=z/y;
printf("After z=z/y: x=%lf, y=%lf, z=%lf\n",x,y,z);
printf("Done\n");
return(0);
}
Second half of the lab:
Next program demonstrates some useful mathematical functions
and the pi (M_PI) constant.
To compile a program that contains #include<math.h>
the option -lm
("Load Math") is required in the command line:
gcc -lm lab3b.c
/*******************************
File lab3b.c
M2120-Fall'05-Lab 3- Thursday
Author: Sergey Sadov
Date: Thursday Sept.22 2005
Math functions in C
********************************/
#include<stdio.h>
#include<math.h> /* Necessary, to provide an access to math functions */
int main()
{
double x;
double y;
double z;
x=0.0; y=0.0; z=0.0;
printf("After initialization: x=%lf, y=%lf, z=%lf\n",x,y,z);
/* In the following fragment we want to find sin(90 degrees) and print
the result */
x=90.0;
z=x*(M_PI/180.0); /*multiplying by conversion factor from degrees to
radians */
y=sin(z); /* sin,cos,tan functions in C work with radian measure */
printf("sin(%lf)=%lf\n",x,y);
/* Next fragment features the "power" function pow. We compute 2 to the
power 3 and print result */
x=3.0;
y=2.0;
z=pow(y,x);
printf("%lf^%lf=%lf\n",y,x,z);
/* To find e to the power x, there is a more efficient method:
as an example we print e squared */
x=2.0;
y=exp(x);
printf("e^%lf=%lf\n",x,y);
printf("Done\n");
return(0);
}