0

この Youtube チュートリアル(以下の関連コードを参照) に従っていると、次のエラーが発生します。

エラー行 6
エラー: '(' の前にコンストラクターのデストラクタまたは型変換が必要です

このエラーの原因と解決方法を教えてください。

#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <time.h>
void myfun(int);//using own function
myfun(8);//pow(4.0,10.0)
using namespace std;
int main()
{
    double num1;
   srand(time(0));// to get a true random number
    double num2;
    num1 = pow(3.0, 9.0);//2 to the power of 4
    cout << num1 <<endl;
    num2 = rand() %100;//random number out of 100
    cout << "\nrandom number = " << num2 << endl ;

    return 0;
}
void myfun(int x)
{

    using namespace std;
    cout << "my favourite number is " << x << endl;
}
4

2 に答える 2

4

これは宣言です:

void myfun(int);//using own function

これは関数呼び出しです:

myfun(8);//pow(4.0,10.0)

コンテキスト外で関数を呼び出すことはできません。

内側に移動してみてくださいmain。何を達成しようとしていますか?

int main()
{
    myfun(8);  //<---- here

    double num1;
    srand(time(0));// to get a true random number
    double num2;
    num1 = pow(3.0, 9.0);//2 to the power of 4
    cout << num1 <<endl;
    num2 = rand() %100;//random number out of 100
    cout << "\nrandom number = " << num2 << endl ;

    return 0;
}
于 2012-07-26T16:59:13.740 に答える
3

ルシアンが言ったように、関数呼び出しをスコープに移動します..この場合はメインです。他にもポイントがあります。次のコードを参照してください。

    #include <iostream>
    #include <cmath>
    #include <stdlib.h>
    #include <time.h>

    void myfun(int);//using own function

    void myfun(int x)
    {
        std::cout << "my favourite number is " << x << std::endl;
    }

    int main()
    {
        double num1, num2;

        srand(time(0));// to get a true pseudo-random number
        num1 = pow(3.0, 9.0);//2 to the power of 4
        std::cout << num1 << std::endl;
        num2 = rand() %100;//random number out of 100
        std::cout << "\nrandom number = " << num2 << std::endl ;
        myfun(8);//pow(4.0,10.0)

        return 0;
    }

カップルポイント:

  • 一般using namespace std;、グローバル スコープで行うのは悪い考えと考えられています。std名前空間が乱雑になり、名前の衝突を避けるために、必要に応じて名前に追加する方がはるかに優れています。
  • srand() は実際には真の乱数を生成しません - 疑似乱数です。
于 2012-07-26T17:20:17.930 に答える