![](/img/trans.png)
[英]error: invalid conversion from ‘int (*)(int, int)’ to ‘int’ [-fpermissive]
[英]invalid conversion from ‘int (*)(int)’ to ‘int’ error?
我正在学习 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’
这是我的代码:
#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;
我相信你的意思是写
r = randn(/* some argument */) + 1; // Note parentheses after randn
问题是您正在尝试调用 function 但忘记放入括号表明您正在拨打电话。 由于您正在尝试滚动六面骰子,因此可能应该阅读
r = randn(6) + 1;
希望这可以帮助!
你有这样的声明:
r=randn+1;
您可能打算调用randn
function,这需要您使用括号并传递一个实际参数:
r=randn(6)+1; // assuming six-sided dice
如果没有括号,符号randn
指的是 function 的地址,并且 C++ 不允许对 function 指针进行算术运算。 function 的类型是int (*)(int)
— 指向接受 int 并返回 int 的 function 的指针。
这可能是答案。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.