-3

I've started learning C this week and I have a problem. I'm trying to let the user enter how many inputs he wants , but the loop will stop when he enter the input -1 . I'm getting the Operand types are incompatible ("float *" and "const char *") error.

#include <stdio.h>
#include <stdlib.h>

void average()
{

    int i;
    float num[100];
    float sum = 0;
    float average = 0;
    int n = sizeof(num)/sizeof(num[0]); 
    //printf("Enter the size of the array: \n");
    //scanf("%d" , &n );



    for (i=0 ; i<n ; i++)
    {
        printf("%d. Enter number: ",i+1);
        scanf("%f",&num[i]);
        sum+=num[i];

        if (num == "-1")
        {
            break;
        }

    }
      average=sum/n;
      printf("Average = %.2f",average);

    }
  • 1
    `num == "-1"` has two different types on each side of the `==` operator. –  Jan 14 '16 at 10:51

1 Answers1

2

This:

if (num == "-1")

is not valid, and is the reason the compiler complains. You're treating num, which is of type float [100], as a pointer to a character (by comparing it to another pointer to character).

You meant:

if (num[i] == -1)

You should do this before adding num[i] to the sum, since the sentinel value -1 should not be part of the total. There's no need to keep an array of the inputs either, and thus no need for num to be an array.

Also, strings in C are compared using strcmp(), almost never with ==.

unwind
  • 391,730
  • 64
  • 469
  • 606