Re: Steve Summit C notes , exercise
- From: Jason Curl <j.m.curl@xxxxxx>
- Date: Sat, 17 Mar 2007 14:08:53 +0100
Martin Ambuhl wrote:
arnuld wrote:it runs fine. i wanted to know if it needs any improvement:
----------------- PROGRAMME ----------------------------
/* Steve Summit's C programming
Section 3 :: exercise 2
STATEMENT:
Write a program to compute the average of the ten numbers 1, 4,
9, ..., 81, 100,
that is, the average of the squares of the numbers from 1 to 10.
/* Since the sum of the squares of the integers 1 ... N is
N * (N + 1) * (2*N + 1) / 6,
and there are N integers in 1 ... N,
we have the following general function.
It could be a macro, instead.
Note the decimal points (there's one extra one
not needed). If the function is not required
to work except with N==10, replace the returned
expression with 38.5
*/
#include <stdio.h> /* not needed for the problem as stated, but
the actal program we will show the value
computed. */
inline double average_of_squares(int n)
{
return (n + 1.) * (2. * n + 1) / 6.;
}
I believe for portable C, we don't want to use 'inline', unless you're using C99. And even then, when I read the spec the it is implementation defined (i.e. it might exist as a keyword and do nothing). Couldn't we expect the compiler to inline this for us anyway at higher optimisation levels?
.
/& To satisfy the requirements of the program, you need only :
int main(void)
{
average_of_squares(10);
return 0;
}
but showing the value computed is probably a good idea: */
int main(void)
{
printf("The average is %g\n", average_of_squares(10));
return 0;
}
- References:
- Steve Summit C notes , exercise
- From: arnuld
- Re: Steve Summit C notes , exercise
- From: Martin Ambuhl
- Steve Summit C notes , exercise
- Prev by Date: Re: dynamic 2 D array with malloc??
- Next by Date: Re: Steve Summit C notes , exercise
- Previous by thread: Re: Steve Summit C notes , exercise
- Next by thread: Re: Steve Summit C notes , exercise
- Index(es):
Relevant Pages
|