no problems now, i corrected it. But why doesn't the floating-point number calculated correctly? Can't i do this:
Code:
printf( "%.2f", 1111 / 25 );
It prints 0.00
But when save the calculation in a float variable and displays it, it's rounded off. Why ?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct listNode {
struct listNode *nextPtr;
int data;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;
void printList( ListNodePtr currentPtr );
int generateList( ListNodePtr *startPtr );
int main()
{
int total;
ListNodePtr startPtr = NULL;
float average;
total = generateList( &startPtr );
average = total / 25;
printList( startPtr );
printf( "\nTotal of all 25 elements is %d", total );
printf( "\nAverage of all 25 elements is %.2f\n\n", average );
getch();
return 0;
}
/* Generate random list - returns sum of all elements */
int generateList( ListNodePtr *startPtr )
{
int randNum, total = 0, i = 0;
ListNodePtr newPtr, currentPtr, previousPtr;
srand( time( NULL ) );
previousPtr = NULL;
currentPtr = *startPtr;
for (; i < 25; i++ ) {
newPtr = malloc( sizeof( ListNode ) );
if ( newPtr != NULL ) {
randNum = rand() % 100;
newPtr->data = randNum;
if ( previousPtr == NULL ) {
newPtr->nextPtr = *startPtr;
*startPtr = newPtr;
}
else {
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
total = total + randNum;
}
else {
printf( "\nNot enough memory.\n\n" );
break;
}
}
return total;
}
/* Print the list */
void printList( ListNodePtr currentPtr )
{
if ( currentPtr == NULL )
printf( "List is empty.\n\n" );
else {
printf( "The list is:\n" );
while ( currentPtr != NULL ) {
printf( "%d --> ", currentPtr->data );
currentPtr = currentPtr->nextPtr;
}
printf( "NULL\n\n" );
}
}