Saturday, September 12, 2020

scores.c --- more advanced version

#include <cs50.h>

 #include <stdio.h>


float average(int length, int array[]);


int main(void)

{

int n=get_int("number of scores:");

int scores[n];

for(int i=0; i<n:i++)

{

scores[i] = get_int("Score %i:", i+1);

}

printf("Average: %.1f\n", average(n, scores))

}


float average(int length, int array[])

{

int sum=0;

for(int i=0;i<length;i++)

{

sum += array[i];

}

return (float) sum / (float) length

}


cs50, lec2


in C, divide float by float and you will get a float

 if you have two integers that you want to divide, but do not want everything after the decimal point to be thrown away, you can type cast so that the computer treats the integers as floats, thereby ending up with more precise results

const int N;

int sum;

average = (float) sum / (float) N;



cs50, lec2



in C, if you divide an integer by an integer, you will get an integer (everything after decimal point is truncated)

 cs50, lec2



global variables are often frowned upon, except for consts

 placed outside of main()

const

and variable name capitalized

....... that is the convention


This is so you wont have to go visually fishing for a certain number value throughout your code int the future.



const variable - do not have hard coded numbers in more than one place (hard to maintain, often source of bugs)

 #include <stdio.h>


const int N = 3;    //make scope global; capital denotes constant


int main(void)

{

int scores[3];

scores[0]=72;

scores[1]=73;

scores[2]=33;


printf("average: i%\n", (scores[0]+scores[1]+scores[2])/N );

}



cs50, lec2