User Tools

Site Tools


haas:fall2019:c4eng:projects:sof0info

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

haas:fall2019:c4eng:projects:sof0info [2019/09/06 14:27] – created wedgehaas:fall2019:c4eng:projects:sof0info [2019/09/06 19:04] (current) – [How do I do math on variables?] wedge
Line 49: Line 49:
 <code c> <code c>
     scores = scores + 4;     scores = scores + 4;
 +</code>
 +
 +=====How about some more math examples?=====
 +Okay, how about taking an average (of four numbers)?
 +
 +<code c>
 +    unsigned char num1  = 0;
 +    unsigned char num2  = 0;
 +    unsigned char num3  = 0;
 +    unsigned char num4  = 0;
 +    float average       = 0.0;
 +    
 +    // prompt for and accept input
 +    fprintf (stdout, "Enter the first number: ");
 +    fscanf (stdin, "%hhu", &num1);
 +    
 +    fprintf (stdout, "Enter the second number: ");
 +    fscanf (stdin, "%hhu", &num2);
 +    
 +    fprintf (stdout, "Enter the third number: ");
 +    fscanf (stdin, "%hhu", &num3);
 +    
 +    fprintf (stdout, "Enter the fourth number: ");
 +    fscanf (stdin, "%hhu", &num4);
 +    
 +    // display the input values
 +    fprintf (stdout, "The average of %hhu, %hhu, %hhu, and %hhu is: ", num1, num2, num3, num4);
 +    
 +    // calculate the average
 +    average = (num1 + num2 + num3 + num4) / 4;
 +    
 +    // display the average
 +    fprintf (stdout, "%.2f\n", average);
 +</code>
 +
 +=====What about formatting in the printf?=====
 +With most types, placing a number between the % and the value will allocate a fixed amount of space on the screen with which to place the output in (if the number takes up less space than the allocated screen space, if it exceeds, it'll overflow it).
 +
 +A positive value is right-justified.
 +
 +A negative value is left-justified.
 +
 +<code c>
 +    int value  = 17;
 +    
 +    fprintf (stdout, "eight spaces:    >12345678<\n");
 +    fprintf (stdout, "right justified: >%8d<\n", value);
 +    fprintf (stdout, "left-justified:  >%-8d<\n", value);
 </code> </code>
haas/fall2019/c4eng/projects/sof0info.1567780032.txt.gz · Last modified: 2019/09/06 14:27 by wedge