简体   繁体   English

输出随机数

[英]Random numbers on output

I am a relative beginner with C++ and currently I am learning how to do functions. 我是C ++的相对入门者,目前正在学习如何使用函数。 Recently I received the following exercise: 最近,我收到了以下练习:

#include <iostream> 
#include <string> 
using namespace std; 

int main(int argc, char* argv[]) 
{ 
    int a,sum=0; 
    cout<<"Enter a number:"; 
    cin>>a; 

    int func(int x);
    sum=func (a );

    cout<<"\n"<<sum;
}

int func(int a)
{
    int x;
    for (int i=0; i<=a; i++)
    {
        x+=i;   
    }
    return x;      
} 

I was already given the int main part of the code in advance, what I need to do is to complete the int func part so the code would execute properly. 我已经预先获得了代码的int主要部分,我需要做的是完成int func部分,以便代码可以正确执行。 If I run this code I just get some random numbers. 如果我运行这段代码,我只会得到一些随机数。 What the func should do is to return the sum of all natural numbers limited by the number imputed by the user. func应该做的是返回受用户估算的数字限制的所有自然数的和。 Could you tell me how would I have to change this code so it would work properly? 您能告诉我如何更改此代码才能正常工作吗? Thank you for any feedback! 感谢您的任何反馈!

Mistake: 错误:

The int x is not initialized so it will lead to undefined behavior and x will give you any random value instead of the correct sum. int x未初始化,因此将导致不确定的行为,并且x将为您提供任何随机值而不是正确的总和。

Possible Solution: 可能的解决方案:

Before you make any increment to the variable x , Initialize it with zero to ensure that it will contain only those values which you want to store. 在对变量x进行任何递增之前,请先将其初始化为零以确保它仅包含要存储的那些值。

Updated Code: 更新的代码:

int func(int a)
{
    int x = 0; //updated statement

    for (int i=0; i<=a; i++)
    {
        x+=i;   
    }
    return x;      
} 

Hope this helps. 希望这可以帮助。

您必须在func主体中初始化x

int x = 0;

int x is not initialized. int x未初始化。 Thus leads to undefined behaviour (This is why you got random numbers). 从而导致未定义的行为(这就是为什么您得到随机数的原因)。 You have to initialize it using one of those: 您必须使用以下方法之一对其进行初始化:

int x=0;
int x(0);
int x{0};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM