WAP to do the following: (E Balagurusamy, Programming In ANSI C, Problem 2-7)
- Declare x and y as integer variables and z as a short integer variable.
- Assign two 6 digit numbers to x and y.
- Assign the sum of x and y to z.
- Output the values of x, y and z.
//E Balagurusamy, Programming In ANSI C,4E
//Exercise 2.7, page 51
//. comments with //scaff indicate code to help during development of code
//. can be safely commented out/removed
//declaring as specified in the problem
int x=0, y=0;
short int z=0;
//assigning two six digit numbers to x and y
z= x + y;
//output code option 1
printf("x = %d\n",x);
printf("y = %d\n",y);
printf("z = x + y = %d",z);
//output code option 2
//evaluating write-time vs read-time convenience,
//as suggested by Code Complete 2
printf("x = %d\ny = %d\nz = x + y = %d",x,y,z);
//calculating ranges of the current machine
bytes_int_current_machine = sizeof(int);
range_int_current_machine = pow(2,(8*bytes_int_current_machine)); //1 byte = 8 bits
printf("\n\n===Some Data To Help Understand===");
printf("\nSize of int on this machine = %d bytes",bytes_int_current_machine);
printf("\nTherefore range of int (2^%d) = %.0f",bytes_int_current_machine, range_int_current_machine); //note %.0f
- when 999999
sum = –31618
- when 111111
sum = 25614
- when 655360
sum = 25342
We are putting int into short and that should clearly jeopardise the results. But why exactly are outputs showing up like this, I can’t figure out right now. Any Ideas?