100 likes | 238 Views
CS1010E Programming Methodology Tutorial 2 Conditional Expressions, Flowcharts. C14,A15,D11,C08,C11,A02. Question 1. double x , y ; x = 0.8 ; y = 0.1 + 0.7 ; printf ( "X = %lf<br>" , x ); printf ( "Y = %lf<br>" , y ); if ( x == y ) printf ( "X and Y are equal!<br>" ); else
E N D
CS1010E Programming MethodologyTutorial 2Conditional Expressions, Flowcharts C14,A15,D11,C08,C11,A02
Question 1 double x, y; x =0.8; y =0.1+0.7; printf("X = %lf\n", x ); printf("Y = %lf\n", y ); if(x == y) printf("X and Y are equal!\n"); else printf("X and Y are not equal!\n"); • Answer: • Because x and y are not fully equal. You can print them out using %.20f to see the difference • Takeaway: • Floating Point number cannot use “==“ sign to test equality ! Question: double z = 0.779; double w = 0.77900000000000002 z == w?
Question 1 (con’t) • How to “solve” (work around) the problem ? • Double cannot define equality in discrete systems • Only approximate measures • If A and B are very close, we say A == B • Compare by difference #define EPS 0.000001 if(fabs(x-y)< EPS){ // x equals to y }else{ // x doesn't equal to y } In this course, 0.000001 is small enough to ensure equality. You should use this number in your LAB
Question 2(a) • What is the output if the input is 3? int main(){ intvalue; scanf("%d",&value); switch(value){ case1:printf("A\n"); case2:printf("B\n"); case3:printf("C\n"); case4:printf("D\n"); default:printf("E\n");break; } return0; } a) The output will be C D E • long a =3l; • switch(a){ • case1:printf("It is 1!\n");break; • case2:printf("It is 2!\n");break; • case3:printf("It is 3!\n");break; • default:printf("Neither\!"); • }
Question 2 (b) Any alternative tricks for “this” question ? #define EPS 0.000001 #define A 1.5 #define B 2.6 #define C 3.7 #define D 4.8 intmain(void){ doublevalue; scanf("%lf",&value); if(fabs(value - A)< EPS)printf("A\n"); elseif(fabs(value - B)< EPS) printf("B\n"); elseif(fabs(value - C)< EPS) printf("C\n"); elseif(fabs(value - D)< EPS) printf("D\n"); else printf("E\n"); return0; } b) Modify your program to scan a floating-point value, and print A if the value is 1.5, B for 2.6, C for 3.7, and D for 4.8. • Switch can only take integers!! • int and char • How to switch on float ? • Using if-else
Question 3 if(a >0) if(a >=1000) a =0; elseif(a <500) a = a *2; else a = a *10; elsea = a +3; • if(a >0) • if(a >=1000) • a =0; • elseif(a <500) • a = a *2; • else • a = a *10; • else • a = a +3; • Is this good? • Logic is clear ? • Easy to maintain ? Indent
Question 3 (con’t) if(a >0) if(a >=1000) a =0; elseif(a <500) a = a *2; else a = a *10; elsea = a +3; if(a >=1000) a =0; elseif(a >=500) a = a *10; elseif( a >0) a = a *2; else a = a +3; If you want add new logic: if a is in [300,500) a = a * 3; Which code is better? a= a * 2 a= a * 10 a= a + 3 a=0 a 0 500 1000
Question 4 (a) • Recall • Start, End • Statement • Condition • Input/output What does this code do ?
Thank you ! • See you next week!