Presentation is loading. Please wait.

Presentation is loading. Please wait.

Representation of Data Types Comparing double and int data types Using integers are faster and more precise round-off errors when using doubles The range.

Similar presentations


Presentation on theme: "Representation of Data Types Comparing double and int data types Using integers are faster and more precise round-off errors when using doubles The range."— Presentation transcript:

1 Representation of Data Types Comparing double and int data types Using integers are faster and more precise round-off errors when using doubles The range of double is from to The storage area of type int contains one binary number The storage area of type double has two parts: Mantissa is binary between (-)0.5 to (-)1 Exponent is an integer number => real number = mantissa * 2 exponent

2 Numerical Inaccuracies Certain fractions cannot be represented in a decimal system: 1/3 = …. Representational errors (round-off error) depends on the number of bits in mantissa => more bits smaller error Equality comparison of two double types can lead to surprising result Representational error affects the result when there is repeated computations: = 5 ?

3 Numerical Inaccuracies Cancellation error can be seen as a result of manipulating very large and small numbers: Manipulating two small numbers may result arithmetic underflow Manipulating two large number may result arithmetic overflow: specially for int data type (- 32,767 to 32,767) => using longint instead of int

4 ACSII Representation of Char Data Type Digits (‘0’-’9’) have the code values of Uppercase letters have consecutive decimal codes from 65 to 90 Lowercase letters have consecutive code values from 97 to 122 Printable characters from 32 to 126 int x; x = ‘1’; printf(“ %d”, x); Result is: 49

5 Arithmetic Expressions Arithmetic expressions uses arithmetic operators for int and double data types. Operators: + and - (can be used also as unary operators),*,/ and %(reminder or mod, which is used only for integer operands) The result type is determined by the operands: = * 2 = * 2.0 = 10.0

6 Operators / and % 7.0 / 2 is 3.5 but 7 / 2 is 3 7 / -2 depends on C compiler 7 / 0 is undefined % returns the integer remainder of division m = (m/n) * n + (m % n) (m % n ) < n 15 % 5 = 0 15 % 6 =3 15 % -7 depends on compiler 15 % 0 is undefined

7 Data Type of Expression If all operands have same data type, the type of expression is same as the type of operands If at least one operand is double, the type of expression is double too The expression, in which the operands are in different data types, is called a mixed-type expression In mixed type assignment (variable = expression) first, the expression is evaluated and then the value of expression is assigned to a variable x = 9 * 0.5 what is the result, if x defined as int? => 4 (only the integral part of 4.5)

8 Rules for Evaluating the Expressions with Multiple Operators What is the result of: (2 + 2) * 4 = ? and * 4 = ? Parenthesis rule All the expressions in the parentheses must be evaluated separately. In the nested parenthesized expressions the inner most expression must be evaluated first. Operator precedence rule: unary +, - first *, /, % next binary +,- last

9 Rules for evaluating Expressions a – b / c * d is evaluated as: a – ((b/c) * d ) Order of execution for the operators in the same precedence group is known as associativity Associativity rule: Unary operators in the same sub-expression at the same precedence level are right associative. It means the evaluation is from right to left. Binary operator in the same sub-expression and in the same precedence level (+ and –,for example) are left associative. It means the evaluations is from left to right

10 Rules for evaluating Expressions 2+2*8 Evaluation tree? | | | | * + PI * radius * radius (p2 – p1) / (t2 – t1) 8 – (3 + 9 / 2) + 2 * - (-5) is equal to: 11

11 Writing Mathematical formula in C Always specify multiplication explicitly with *. For example: b 2 – 4acb * b – 4 * a * c Use parenthesis to control the order of operator evaluation. For example for division: (a + b) / (c + d) Two arithmetic operators can be written in succession if the second is unary operator a × - (b + c)a * - (b + c)

12 Conversion of Data Types What are the results: double z = 5 / 4 => z = 1.0 int n = 1.2 * 1.2 => n = 1 double avg = (double) 15 / 6 => avg = 2.5

13 Conversion of Data Types Automatic conversion  In an expression, if one operand is double, then the result is a double  In an assignment statement variable = expression, if variable is double and expression is int, then the result will be converted to double If variable is int and expression is double the result converted to int and fractional part is lost

14 Conversion of Data Types Explicit conversion or cast has the highest precedence double x; x = 15 / 6; => x= 2.0 x = (double) 15 / (double) 6; => x=2.5 x := (double) 15 / 6 ; => x= 2.5 x = (double) (15 / 6); => x=2.0

15 /* Computes a test average */ #include int main(void) { int total_score, num_students; double average; printf("Enter sum of students' scores> "); scanf("%d", &total_score); printf("Enter number of students> "); scanf("%d", &num_students); average = (double)total_score / (double)num_students; printf("Average score is %.2f\n", average); return (0); } Enter sum of students' scores> 1822 Enter number of students> 25 Average score is 72.88

16 Case Study: Quality Control in Manufacturing Flat Washers Problem: Establish an initial quality control check for ½-inch flat washers. The program will compute the difference between the expected and observed areas and will print the difference as a percentage of the expected area.

17 Case Study: Quality Control Analysis: Data Requirements: Constants: PI WASHER_DIAMETER (1.0/2.0) OUTER_DIAMETER (17.0/16.0) Input: double observed_area; Output: double pct_differ; Program Variables: double washer_radius; double outer_radius;double rim_area; Relevant Formulas: area =PI * radius ^2, radius = 0.5 diameter, percentage difference of 2 areas: = ((expected area – observed area) / expected area) * 100 (relative error)

18 Case Study: Quality Control Design Initial Algorithm: 1. Get observed area of washer rim 2. Compute expected area of rim 2.1 compute washer_radius 2.2 compute outer-radius 2.3 compute rim-are = PI * outer-radius *outer-radius – PI * washer_radius* washer_radius 3.Compute percentage difference between expected and observed area 3.1 pct_differ = ((expected area – observed area) / expected area) * Display percentage difference Implementation

19 #include #define WASHER_DIAMETER (1.0/2.0) /* diameter in inches of a flat washer (diameter of the hole) */ #define OUTER_DIAMETER (17.0/16.0) /* diameter of edge of outer rim of a WASHER_DIAMETER-inch flat washer */ #define PI int main(void) { double observed_area; /* input - observed_area (in square inches) of a washer rim */ double pct_differ; /* output - amount of difference between observed and expected rim size, as a percentage of expected size*/ double washer_radius; /* expected washer_radius (radius of hole) */ double outer_radius; /* expected radius of washer rim's outer edge */ double rim_area; /* expected area of washer rim */ /* Get observed_area of washer rim */ scanf("%lf", &observed_area);

20 printf("Observed_area = %.4f sq. in.\n", observed_area); /* Compute expected area of rim */ washer_radius = 0.5 * WASHER_DIAMETER; outer_radius = 0.5 * OUTER_DIAMETER; rim_area = PI * outer_radius * outer_radius - PI * washer_radius * washer_radius; /* Compute percentage difference between expected and observed rim area */ pct_differ = (rim_area - observed_area) / rim_area * 100; /* Display percentage difference */ printf("Expected area differs from observed area by %.2f percent.\n", pct_differ); return (0); } Observed area = sq. in. Expected area differs from observed area by percent.

21 Case Study: Quality Control Testing: Run with a data file containing a few different observed sizes Output should be modified as: printf("Expected area (%.4f sq. in ) differs from”, rim_area); printf(“observed area by %.2f percent. \n”, pct_differ);

22 Function Implementation How we can translate the expressions with Sqrt and Absolute value in C? ( for example: ax 2 + bx + c = 0, a 2 = b 2 + c 2 – 2bc sin(α) program units called functions Using functions allows reusing of other programs. Functions act as black boxes that get input (input arguments) and produce a result (function result) For example: #include(math,h) a = sqrt(first) b = sqrt(second) c= sqrt(a + c)

23 /* Performs three square root computations */ #include /* definitions of printf, scanf */ #include /* definition of sqrt */ int main(void) { double first, second, /* input - two data values*/ first_sqrt, /* output - square root of first input value*/ second_sqrt, /* output - square root of second input */ sum_sqrt; /* output - square root of sum*/ /* Get first number and display its square root.*/ printf("Enter a number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("The square root of the number is %.2f\n", first_sqrt);

24 /* Get second number and display its square root.*/ printf("Enter a second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("The square root of the second number is %.2f\n", second_sqrt); /* Display the square root of the sum of the two numbers.*/ sum_sqrt = sqrt(first + second); printf( "The square root of the sum of the two numbers is %.2f\n", sum_sqrt); return (0); } Enter a number> 9.0 The square root of the number is 3.00 Enter a second number> 16.0 The square root of the second number is 4.00 The square root of the sum of the two numbers is 5.00

25 Predefined Functions NamePurpose Argument(s) Return type fabs(x) Returns the absolute value of x double double abs(x) Returns the absolute value of x int int rand() Returns a random integer none int between 0 and RAND_MAX a constant defined in stdlib,h

26 User-Defined Functions Allows programmers to define special purpose functions with the same advantages of C’s library functions. Some of the advantages of using functions are: Changing the program into separate pieces Code reusing Easier modification and maintenance of the program More understandable program

27 User-Defined Functions A function is a grouping of program statements into a single program unit. It must be declared before it can be referenced. One way of declaration is to insert a function prototype before the main function Function prototype defines the data type of that function (type of the return value), function name and information about the arguments that the function expects.

28 User-Defined Functions The format for defining a function prototype is: ftype fname(argument list); For example: void instruct(void) is placed before the main function and shows instruct function that has no arguments and return value (void) Inside the main function, instruct can be called as: instruct (); Function definition, which is placed after the main function, specifies the function operation.

29 User-Defined Functions The function definition has the same heading as function prototype except for “;” symbol ftype fname(argument list) { executable statements; } Example: void print_star(void) { printf(“ ************* \n”);}

30 /*Performs three square root computations*/ #include /* definitions of printf, scanf */ #include /* definition of sqrt */ void instruct(void); /* Displays user instructions */ int main(void) { double first, second, /* input - two data values*/ first_sqrt, /* output - square root of first input value */ second_sqrt, /* output - square root of second input */ sum_sqrt; /* output - square root of sum*/ /* Display instructions.*/ instruct(); /* Get a number and display its square root.*/ printf("Enter a number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("The square root of the number is %.2f\n", first_sqrt);

31 /* Get second number and display its square root.*/ printf("Enter a second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("The square root of the second number is %.2f\n",second_sqrt); /* Display the square root of the sum of the two numbers.*/ sum_sqrt = sqrt(first + second); printf( "The square root of the sum of the two numbers is %.2f\n", sum_sqrt); return (0); }

32 /* * Displays user instructions */ void instruct(void) { printf("This program demonstrates the use of the \n"); printf("math library function sqrt (square root).\n"); printf("You will be asked to enter two numbers --\n"); printf("the program will display the square root of \n"); printf("each number and the square root of their sum.\n\n"); }

33 User-Defined Functions Transfer of Control in function call When the computer executes a function call statement, it transfers control to the function definition. In the function definition after execution of the last statement in the function body, computer returns the control to the main program and executes the next statement after the function call. Example : instruct();  instruct (void) prinf(“Enter a number> “)  { ……}

34 User-Defined Functions Common programming errors with functions Not using #include preprocessor directive for the predefined functions Not defining a prototype before the main and definition after the main for the user defined functions Not using the correct order and type for the arguments of the functions Dividing by zero in the function body

35 #include int main(void) { int first, second; double temp, ans; printf("Enter two integers> "); scanf("%d%d", &first, &second); temp = second / first; ans = first / temp; printf("The result is %.3f\n", ans); return (0); } Enter two integers> 14 3 Arithmetic fault, divide by zero at line 272 of routine main Or in another environment the wrong result can be print: Enter two integers> 14 3 The result is 1.#IO


Download ppt "Representation of Data Types Comparing double and int data types Using integers are faster and more precise round-off errors when using doubles The range."

Similar presentations


Ads by Google