12_c-prog

is forgiving about f vs lf etc but not so with scan

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: exit() – we are using s scanf() to scan a value into a variable – the & symbol before the variable name points to that variables memory address so s scanf k nows where to put the value – printf ( and sprintf, f printf, etc.) is forgiving about % f vs % lf, etc., but not so with scan functions (scanf, sscanf, fscanf, etc.) Winter 2008 • k++ adds one to variable: same as k += 1; s ame as k = k + 1; – – – – – 13 adds one to c ount each time (see rule above) “mods” c ount by 4 (remainder of count/4) output is: 1, 2, 3, 0, 1, 2, 3, 0, 1, 2 could (and often do) use k as int value within loop for (;;) is a way to get an indefinite loop (Ctrl-C to quit) Winter 2008 14 UCSD: Physics 121; 2008 UCSD: Physics 121; 2008 Math Math Warnings #include <math.h> … double x,y,z,pi,ampl=3.0,sigma=1.2; • Number one mistake by C newbies: disrespecting newbies: variable type int i,j=2,k=3; double x,y,z; pi = 3.14159265358979; x = sin(60.0*pi/180.0); y = sqrt(fabs(2*x + pi)); z = ampl*exp(-0.5*pow(x/sigma,2.0)) i x y z • Notes: – Must include math.h = = = = 2/3; 2/3; 2/3.0; 2.0/3; printf("i = %d; x = %f; y = %f; z = %f; other = %f\n",i,x,y,z,j/k); • if compiling on linux/unix, use - lm flag to link math – note mixed assignment in variable declarations – fabs is “floating absolute value”, and here keeps s qrt from getting a negative argument • otherwise result could generate NaN ( Not a Number) – pow(x,y) raises x to the y power (x y) i = 0; x = 0.000000; y = 0.666667; z = 0.666667; other = 0.000000 – i is an integer, so 2/3 truncates to zero – even though x is a double, 2/3 performs integer math, then converts to double • “other” value in p rintf shows same is true if j/k used – as long as one value is a float, it does floating-point math Winter 2008 Lecture 12 15 Winter 2008 16 4 C-Programming, Part 1 02/26/2008 UCSD: Physics 121; 2008 Casting Talking to the Parallel Port in Windows • when necessary, one may “cast” a value into a type cast” of your choice:...
View Full Document

Ask a homework question - tutors are online