1. Type in and run the all programs presented in lecture note 7 and 8. Briefly describe the theory/ concept you learned from these program separately.
Lecture note 06: Type Casting, Command Line Arguments and Defining Constants
- Type Casting
Code 1
#include <stdio.h>
int main()
{
int sum = 17, count = 5;
double mean;
mean = sum / count;
printf("Value of mean : %f\n", mean );
return 0;
}
Result
Value of mean : 3.000000
Code 2
#include <stdio.h>
int main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );
return 0;
}
Result
Value of mean : 3.400000
Code 3
#include <stdio.h>
int main()
{
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
return 0;
}
Result
Value of sum : 116
Code 4
#include <stdio.h>
int main (void)
{
float f1 = 123.125, f2;
int i1, i2 = -150;
char c = 'a';
/* floating to integer conversion */
i1 = f1;
printf ("%f assigned to an int produces %i\n", f1, i1);
/* integer to floating conversion */
f1 = i2;
printf ("%i assigned to a float produces %f\n", i2, f1);
/* integer divided by integer */
f1 = i2 / 100;
printf ("%i divided by 100 produces %f\n", i2, f1);
/* integer divided by a float */
f2 = i2 / 100.0;
printf ("%i divided by 100.0 produces %f\n", i2, f2);
/* type cast operator */
f2 = (float) i2 / 100;
printf ("(float) %i divided by 100 produces %f\n", i2, f2);
return 0;
}
Result
123.125000 assigned to an int produces 123
-150 assigned to a float produces -150.000000
-150 divided by 100 produces -1.000000
-150 divided by 100.0 produces -1.500000
(float) -150 divided by 100 produces -1.500000
*Type casting is when you tell the computer to change the type of a value to another type. For example, if you have a big number but you only need a smaller number, you can use type casting to make it fit. However, be careful: if the number is too big for the new type, you might lose some information. Also, if you have a decimal number and you change it to a whole number, you'll lose the decimal part.
- Command Line Arguments
No comments:
Post a Comment