-2

代码是:

  int main() {
    int n, largest = 1;
    cout << "enter :" << endl;
    cin >> n;
    int i = n - 1;
    while(i > 0) {
       if (n % i == 0){
            largest = i;
       }
       i--;
    }
    cout << largest << endl;
    system("pause");
    return 0;
  }

为什么会出现这些错误?这段代码不断出错,我的教授说我应该添加一个布尔表达式。但我不知道为什么以及在哪里添加它?

4

2 回答 2

2

(Inspired by Alexandrescu's CppCon 2019 talk)

Recall, that the control check on the loop is not necessary - we know that X % 1 is 0 for any X. Also, in-line with Alexandrescu's commitment to endless loops, we could rewrite the loop as following (it will have an added bonus of making it correct, but also will improve it's performance):

if (n <= 1) {
    return;
}
largest = n - 1;
for (;; --largest) {
    if (n % largest == 0)
        break;
}

// Here largest is usable
于 2019-09-25T19:05:13.613 回答
0

重写这个循环

while( i > 0){
    if ( n % i == 0){
        largest = i;
    }
    i --;
}

例如喜欢

while( i > 0 && n % i != 0 ) i--;

if ( i ) largest = i;

此外,您应该使用 unsigned int 类型而不是 int 类型。否则用户可以输入负数。在这种情况下,循环没有意义。

使用您的方法,该程序可以看起来例如以下方式

#include <iostream>

int main() 
{
    unsigned int n = 0, largest = 1;

    std::cout << "enter a non-negative number: ";

    std::cin >> n;

    if ( n != 0 )
    {
        unsigned int i = n - 1;

        while ( i > 0 && n % i != 0 ) i--;

        if ( i ) largest = i;
    }

    std::cout << "The largest own divisor is " << largest << std::endl;

    return 0;
}
于 2019-09-25T18:58:53.710 回答