Home > Back-end >  how does adding a line of prtintf fix this?
how does adding a line of prtintf fix this?

Time:10-17

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:

  1. You are adding a float and an int when you do: tulos = tulos lista[rivi];, without casting the input float to int like this: tulos = tulos (int)lista[rivi]; Or better yet, just declare tulos as float, and return a float from your laske function, because the return value is again being assigned to a float yhteispisteet

  2. You assign to lista[counter ] with the scanf, and then increment the counter (post-increment) and print the lista[counter](which is printing the incremented indexed value that did not take any assignments yet). It is better to increment counter after the printf function.

  3. 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 the printf and then rerun

  •  Tags:  
  • c
  • Related