从' int (*)(int) '到' int '的无效转换错误
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
问题是,你试图调用函数,但忘记放入括号,表明你正在进行调用。因为你要掷一个六面骰子,这应该是
r = randn(6) + 1;
希望这对你有帮助!
你有这样的语句:
r=randn+1;
您可能想要调用 randn
函数,这需要您使用括号并传递一个实际的参数:
r=randn(6)+1; // assuming six-sided dice
如果没有括号,符号randn
指的是函数的地址, c++不允许对函数指针进行算术运算。该函数的类型为int (*)(int)
——指向接受int型并返回int型的函数的指针。
这可能就是答案。
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;
}
相关文章:
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度