I am new to the C language (I started to learn it a week ago). the program was having some random output so i wanted to see what was it storing in the variable. then the printf fixed it somehow.
#include <stdio.h>
int laske(float lista[]);
const int MAX = 3;
int main()
{
float lista[5], yhteispisteet;
int counter = 0;
do
{
printf("Anna %d. pisteet: \n", counter 1);
scanf("%f", &lista[counter ] );
printf("%d",lista[counter]); <-- if you remove this line it dosent work
}
while (counter < MAX);
yhteispisteet = laske(lista);
printf("\nYhteispisteet ovat: %.2f\n", yhteispisteet);
getchar();
return 0;
}
int laske(float lista[])
{
int rivi, tulos;
for (rivi=0; rivi< MAX; rivi )
tulos = tulos lista[rivi];
return tulos;
}
CodePudding user response:
Three things to note from your code:
You are adding a
floatand anintwhen you do:tulos = tulos lista[rivi];, without casting the input float to int like this:tulos = tulos (int)lista[rivi];Or better yet, just declaretulosasfloat, and return a float from yourlaskefunction, because the return value is again being assigned to a floatyhteispisteetYou assign to
lista[counter ]with thescanf, and then increment the counter (post-increment) and print thelista[counter](which is printing the incremented indexed value that did not take any assignments yet). It is better to incrementcounterafter the printf function.You did not initialize your variable
tulos, and this gives you undefined behavior when your code is running, which is probably what you are seeing when you add and then remove theprintfand then rerun
