简体   繁体   中英

invalid conversion from ‘int (*)(int)’ to ‘int’ error?

I am learning C++ and one of the programs was for a random number generator.
Once I wrote the program I got the following errors:

dice.cpp: In function ‘int main()’:
dice.cpp:18: error: pointer to a function used in arithmetic
dice.cpp:18: error: invalid conversion from ‘int (*)(int)’ to ‘int’

Here is my code:

#include<iostream>
#include<cmath>
#include<stdlib.h>
#include<time.h>
using namespace std;
int randn(int n);
int main()
{
  int q;
  int n;
  int r;
  srand(time(NULL));
  cout<<"Enter a number of dice to roll: ";
  cin>>n;
  cout<<endl;

  for (q=1; q<=n; q++)
  {
    r=randn+1;  // <-- error here
    cout<<r<<endl;
  }
  return 0;
}

int randn(int n)
{
  return rand()%n;
}

What could be the problem?

I believe that your problem is this line:

r=randn+1;

I believe that you meant to write

r = randn(/* some argument */) + 1; // Note parentheses after randn

The issue is that you're trying to call the function but forgetting to put in the parentheses indicating that you're making the call. Since you're trying to roll a six-sided die, this should probably read

r = randn(6) + 1;

Hope this helps!

You have this statement:

r=randn+1;

You probably meant to call the randn function, and that requires that you use parentheses and pass an actual argument:

r=randn(6)+1; // assuming six-sided dice

Without parentheses, the symbol randn refers to the address of the function, and C++ doesn't allow arithmetic operations on function pointers. The type of the function is int (*)(int) — pointer to a function accepting an int and returning an int.

This could be the answer.

int main()
{
   int q;
   int n;
   int r;
   srand(time(NULL));
   cout<<"Enter a number of dice to roll: ";
   cin>>n;
   cout<<endl;

   for (q=1; q<=n; q++)
   {
      r=randn(6)+1;  // <-- u forget to pass the parameters
      cout<<r<<endl;
   }
   return 0;
}

int randn(int n)
{
   return rand()%n;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM