簡體   English   中英

從“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

問題是您正在嘗試調用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM