Arian Motamedi
Arian Motamedi

Reputation: 7423

Finding Perfect Numbers in C - Compile Error

I'm writing a simple program that finds the perfect numbers up to a given range. Here's what I have:

#include<sys/types.h>
#include<sys/time.h>
#include<time.h>
#include<errno.h>
#include<fcntl.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<strings.h>    
#include<unistd.h>


void Compute(double range);

int main(int argc, char** argv[])
{
  double range = 40000000;

  printf("range: %f\n", range);

  Compute(range);
}

void Compute(double range)
{
  double numbers[range];

  double total = 0;
  double sum = 0;
  double num;
  double j;

  for(num = 1; num < range; num++){
    sum = 0;

    for(j = 1; j < num; j++){
      if((num % j) == 0){
        sum+=j;
      }
    }

    if(sum == num){
      numbers[total] = sum;
      total++;
    }

  } 

  printf("Total: %f\n", total);

  for(j = 0; j < total; j++){
    printf("%f \n", numbers[j]);
  }

}

However, when I try to compile the program, I keep getting error: expression must have integral type error for almost all the operations in the Compute() method. It works fine for integer data types, but not for double. I'm using Intel C Compiler. Any ideas why the compiler is complaining?

Upvotes: 0

Views: 201

Answers (3)

melpomene
melpomene

Reputation: 85837

I'm not sure you know what double means.

For example: what exactly would you expect double numbers[1.23]; to do? (rhetorical question)

The % operator also requires integer operands (you can use fmod() to get a fractional modulus, but I doubt that's what you want).

Upvotes: 3

William Morris
William Morris

Reputation: 3684

Your array:

double numbers[range];

needs in integral size for the array. Use a cast such as.

double numbers[(int)range];

Same with your other uses of double variables.

Upvotes: 1

mathematician1975
mathematician1975

Reputation: 21351

You cannot create an array with a floating point size

double numbers[range];

the argument must be an integer. Imagine if range was 2.5 - C won't allow an array of 2.5 doubles. An array must have an integer number of elements

Upvotes: 7

Related Questions