从“int(*)(int)”到“int”的转换无效错误? 我正在学习C++,其中一个程序是随机数生成器。 编写程序后,我发现以下错误: 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’

从“int(*)(int)”到“int”的转换无效错误? 我正在学习C++,其中一个程序是随机数生成器。 编写程序后,我发现以下错误: 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’,c++,C++,这是我的密码: #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:

这是我的密码:

#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;
}

有什么问题吗?

您有这样的说法:

r=randn+1;
您可能打算调用randn函数,这需要使用括号并传递实际参数:

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

没有括号,符号RANN指函数的地址,C++不允许函数指针上的算术运算。函数的类型是int*int-指向接受int并返回int的函数的指针。

我认为您的问题在于这一行:

r=randn+1;
我相信你是有意写作的

r = randn(/* some argument */) + 1; // Note parentheses after randn
问题是,您试图调用该函数,但忘记在括号中加上表示正在进行调用的括号。由于您正在尝试滚动一个六面骰子,因此可能应该阅读以下内容

r = randn(6) + 1;

希望这有帮助

这可能就是答案

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;
}

也许你是C++新手,但是这个骰子。CPP:18:错误:指向函数中使用的函数的指针很难被误解。你是否试过阅读错误并查看代码的第18行?@ PruteRoIn,如果你对C++如此陌生,就不容易理解,因为你不知道指针是什么。那么这个信息就是胡言乱语。另一方面,如果你忽略了文本,只是假装它说在这一行或之前不久有一个错误,那么去复习你的课堂讲稿,它仍然是一个很好的指示器。错误:指向算术中使用的函数的指针randn是指向程序中某个函数的名称,这样你就可以调用该函数了。您在函数名中添加了一个数字。错误:“int*int”到“int”的转换无效,当您看到括号在*int类型中接触时,表示它是一个函数名。它无法将函数名转换为整数,以进行数学运算。