使用未初始化的局部变量?还没有初始化?有什么问题

时间:2018-11-08 16:37:43

标签: c++

为什么我已经初始化了第二个函数,但为什么我仍会使其保持未初始化状态?

  

错误C4700未初始化的局部变量'x1'
  错误C4700未初始化的局部变量'x2'

#include <iostream>
using namespace std;
bool is_prime(int n, bool is_prime = 0)
{
    for (int i = 2; i < n; i++)
    {
        bool is_prime = true;
        if (n % i == 0)
            is_prime = false;
    }
    return is_prime;
}

int sumPrime(int , int )
{
    int x1, x2; // keeps saying its unitialized

    int sum = 0;
    for ( x1; x1 < x2; x1++)
    {
        if (is_prime(x1))
        {
            sum += x1;
        }
    }
    return sum;
}

int main()
{
    int n1, n2;
    cout << " enter two ns" << endl;
    cin >> n1 >> n2;
    cout << sumPrime(n1, n2) << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:4)

您好奇的参数语法

int sumPrime(int , int )
{
    int x1, x2;

来自预先标准化的C语言(尽管我不知道会编译此特定变体的旧编译器),并且从未将其转换为C ++。

您需要

int sumPrime(int x1, int x2)

答案 1 :(得分:3)

您的代码中存在各种问题:

is_prime()函数应类似于:

bool is_prime(int n) // <-- No use of 'is_prime' parameter here...
{
    bool is_prime = true; // should be outside the loop...
    for (int i = 2; i < n; i++)
    {
        if (n % i == 0)
            is_prime = false;
    }
    return is_prime;
}

sumPrime()函数:

int sumPrime(int x1, int x2)
{
    /*int x1, y1; Just forget these variables, they are not even initialized*/
    int sum = 0;
    for ( /*x1 <- It is not syntatically correct, it is not an expression, so just leave it blank*/; x1 < x2; x1++)
    {
        if (is_prime(x1))
        {
            sum += x1;
        }
    }
    return sum;
}

说明:

is_prime()函数...,您在这里所做的是声明了变量is_prime 不是函数,请仔细查看 )既在参数中也在循环内...

这实际上不会造成问题,但是会遮盖您先前的声明...

此外,不需要is_prime 出现在参数中,因为它几乎没有用也许是因为我没有知道您要达到的目标)...但是您必须选择一个,所以您可以可以做这样的事情:

bool is_prime(int n, bool& is_prime) // Make is_prime a reference and assign to it...

此外,更改此行:

bool is_prime = true;

收件人:

is_prime = true; // Remove bool specifier, don't declare 'is_prime' again!

关于其他函数,实际上,它甚至都不是旧语法,甚至不问C ++,在C ++中declare functions的唯一方法是:

<return_type> <function-name>(<parameters>) { <body> }

请注意,这是函数声明的伪语法,当今大多数语言都遵循该语法...

因此,您的功能也应如下所示:

bool is_prime(int x1, int x2) { /* <body> */ }

还要删除函数中的 x1 x2 的声明,以防止variable shadowing(就像上面的示例一样) ...


  

编辑:另外,看着这些小错误,任何人都会告诉你要看一个好的C++ book ...

相关问题