Difference between revisions of "CSC231 Mystery C Program with signed numbers"

From dftwiki3
Jump to: navigation, search
(Mystery Program)
(Mystery Program)
Line 59: Line 59:
 
=Solution=
 
=Solution=
 
<br />
 
<br />
 +
;Answer 1
 
* First we need to find the unsigned version of -32756, because that is the value we expected, but this value is too large to be represented in 2's complement.
 
* First we need to find the unsigned version of -32756, because that is the value we expected, but this value is too large to be represented in 2's complement.
 
* The difference between a negative 16-bit number in 2's complement, and its unsigned equivalent is 2<sup>16</sup>, of 65536.
 
* The difference between a negative 16-bit number in 2's complement, and its unsigned equivalent is 2<sup>16</sup>, of 65536.
Line 66: Line 67:
 
* Therefore x = 32700
 
* Therefore x = 32700
 
* Plug these numbers in the program and verify that we get, indeed, the two numbers listed in the comment section of the program.
 
* Plug these numbers in the program and verify that we get, indeed, the two numbers listed in the comment section of the program.
 +
<br />
 +
;Answer 2
 +
* We could switch from shorts to ints
 +
* We could use unsigned shorts
 
</onlydft>
 
</onlydft>
  

Revision as of 08:19, 13 November 2014


Mystery Program

  • The program below is incomplete.
  • The two values that were used to initialize x and y have been removed.
  • We do have the output of the program, though, corresponding to the original x and y values.


Question 1
Figure out the value of x and y in the original program.


Question 2
Find a way to fix the program so that it outputs the correct information


You may use this converter to help you out...

/* mystery.cpp
// D. T.
// mystery program
// To compile and run this program:
//
//     g++ mystery.cpp
//     a.out
//
// The output of the program is the following
//
// 32740
// -32756
//
// With what positive values were x and y initialized
// at the beginning of the program.  Explain why.
// (a short int contains 16 bits)
*/

#include <stdio.h>

int main() {

    short int x = ???? ;
    short int y = ???? ;

    x = x+y;
    printf( "%d\n", x );

    x = x+y;
    printf( "%d\n", x );

    return 0;
}


For reference, 215 = 32768.


...




















Solution! </onlydft>