试图跟随Bucky教程

时间:2012-07-26 16:58:00

标签: c++

在关注this Youtube tutorial时(请参阅下面的相关代码),我收到以下错误:

  

错误行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;
}

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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()实际上并不生成一个真正的随机数 - 只是一个伪随机数。
相关问题