c++ - 丰富的数字测试

标签 c++ loops menu numbers

如果自然数 n > 0 的真约数之和(包括 1 但不包括 n 本身)大于其自身,则称该自然数为丰富数。例如,数字12是一个丰富的数字,因为它的约数之和(包括1但不包括12本身)是1+2+3+4+6=16,大于12本身。作为对比,数字 6 不是一个丰富的数字,因为它的约数之和(包括 1 但不包括 6 本身)是 1+2+3=6,它不大于 6 本身。在此处查看更多示例和说明。

好像每次用户输入一个数字,它总是很丰富。对需要做什么有什么建议吗?

    // If the user selects option "a"
    if (option == 'a')
    {
        bool abundantTest(int n);
        {
            int n, i = 1, sum = 0;
            cout << "Enter a number: " << endl;
            cin >> n;

            while (i < n){
                    if (n % i == 0)
                        sum = sum + i;
                        i++;
            }

            if (sum == n){
                cout << i << " is not an abundant number." << endl;
            }
            else{
                cout << i << " is an abundant number." << endl;
            }

        }
    }

最佳答案

也许你只是想检查一下

if (sum <= n)

小于或等于大于相反。

你还可以:

if (sum > n)
    cout << i << " is an abundant number." << endl;
else
    cout << i << " is not an abundant number." << endl;

简单地说:

cout << i << " is " + std::string(sum > n ? "" : "not ") + "an abundant number." << endl;

关于c++ - 丰富的数字测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245938/

相关文章:

C++ -- Detours (Win32 API Hijacking) -- 劫持类方法

javascript - Angular 2/ES6/根据属性过滤对象对象

javascript - 如何避免使用此函数污染全局命名空间?

html - 如何让父 div 成为其子项的高度?

c++ - 链接器无法在命名空间中找到函数定义

c++ #define 并连接大小写(我使用的是 gcc)

c++ - 编译要在 C++ 版本中链接的 C 库...是否需要指定 C++ 标准?

javascript - 在 Javascript 中通过多个 if 语句运行 While 循环

javascript - 菜单点击显示具有相同 id : variable scope issue? 的 div

html - 没有javascript的下拉菜单