【问题标题】:printing out the first 888 happy numbers打印出前 888 个快乐数字
【发布时间】:2017-02-13 20:51:40
【问题描述】:

所以我有这个函数来检查一个数字是否是一个快乐的数字。它返回真或假。

bool is_happy(int x) //Let the function determine if the number is happy
{

int result;
while (x != 1) //If x == 1, it is a happy number
{
    result = 0;
    while (x) //Until every digit has been summed
    {
        result += (x % 10) * (x % 10); //Square digit and add it to total
        x /= 10;
    }
    x = result;
    if (x == 4) //if x is 4, its a sad number
        return false;
}
return true;
}

它按预期工作,当 X 是一个快乐的数字时返回 true。

我要做的是打印前 888 个快乐数字。

我尝试设置一个 while 循环,其中包含一个递增的整数 b

int b=0;
while(b<=888) {
b++;
}

但是,我不确定如何包含和增加 X,每当我尝试包含和增加 x 时,它只会打印出第一个快乐数字 888 次。

我的问题是试图增加 x,每当它达到一个快乐的数字时,它就会输出那个快乐的数字,然后增加 b。我只能使用 iostream 而不能使用其他库。

编辑:对缺乏清晰度表示歉意!

我正在尝试打印前 888 个快乐数字,我有检查数字是否快乐的功能。我正在尝试创建一个循环,打印出使函数返回 True 的前 888 个数字。

非常感谢!

【问题讨论】:

  • 在代码中显示您的尝试

标签: c++ increment iostream


【解决方案1】:

试着遵循这个逻辑。

首先,为计数器创建一个变量。假设int counter = 0;

然后,做:

while ( counter < 888 )
{

  if ( number == /*happy condition*/)
  {
    //do somehting
    counter++;
  }


  else
  {
    // :(
  }

}

【讨论】:

    【解决方案2】:

    您需要分别递增这两个数字:

    int b = 0;
    for (int x = 1; b < 888; x++) {
        if (is_happy(x)) {
            // print
            b++;
        }
    }
    

    【讨论】:

      【解决方案3】:

      您需要将 b 传递给您的函数,并保持对快乐数字的计数:

        int b = 0;
        int count = 0;
        while( count < 888 ) {
            if (  is_happy( b ) ) {
               // do something
               count++;
            }
            b++;
        }
      

      【讨论】:

      • 这就是复制和粘贴的地方。固定。
      猜你喜欢
      • 2021-05-27
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多