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

正如 Luchian 所说,将函数调用移动到范围内 .. 在本例中为 main。我还有其他几点。请参阅以下代码。

    #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 回答