C ++重写嵌套if else语句,带有函数

时间:2015-11-12 17:05:30

标签: c++ if-statement

我正在开发一个程序,打印所有可被自身整除的数字。我试图避免在我的代码中使用if else语句重复。我想把这段代码转换成适应输入的数字。 我试过做

while ( x % x == 0)

但它只返回每个数字。 我也试过

int& x = y

复制x并使用x % y,但它与x % x相同。

else if(x == y)
{
    cout << "Printing numbers divisible by " << x << endl;

    while(x <= 1000)
    {
        y = x;

        while(x % y == 0)
        {
            cout << x << " ";
            break;
        }

        x++;
    }
}
else if(x == 2)
{
    cout << "Printing numbers divisible by " << x << endl;

    while(x <= 1000)
    {
        y = x;

        while(x % y == 0)
        {
            cout << x << " ";
            break;
        }

        x++;
    }
}

3 个答案:

答案 0 :(得分:2)

int &x = y;

不执行副本,它是一个参考(阅读相关内容)。有了它,y指的是x的内存位置,因此它具有相同的值。您需要一份副本(xy相互独立),所以必须是

int x = y; // so easy?

好的,但是你用相反的方式写了一下来搞砸了一些东西。所以,它应该是

int y = x;

if(x % y == 0) { ... }

答案 1 :(得分:1)

尝试:

/**
 * prints number from x to 1000 that are divisible by x
 * @param x divisor
 */
void print_divisible_to_1k(int x)
{
    using namespace std;

    int i = x; /* from i to 1000 */

    cout << "Printing numbers divisible by " << x << endl;

    while ( i <= 1000 )
    {
        if ( i % x == 0 ) /* use if statement not while loop */
        {
            cout << i << " ";
        }

        i++;
    }
}

或者,这是解决方案的问题更多版本,感谢@ Jarod42:

/**
 * prints number from x to 1000 that are divisible by x
 * @param x divisor
 */
void print_divisible_to_1k(int x)
{
    using namespace std;

    cout << "Printing numbers divisible by " << x << endl;

    /* a more problem-aware programming solution via @Jarod42 */
    for ( int i = x; i <= 1000; i += x)
    {
        cout << i << " ";
    }
}

答案 2 :(得分:0)

试试这个

 int main()
{
  int n, i, flag=0;
  cout << "Enter a positive integer: ";
  cin >> n;
  for(i=2;i<=n/2;++i)
  {
      if(n%i==0)
      {
          cout << "This is divisible by "+i;
      }
  }
}
相关问题