【问题标题】:Sudden Break in the while loop in Program to find Factors程序中的while循环突然中断以查找因素
【发布时间】:2016-05-02 16:50:29
【问题描述】:

我正在编写一个代码,它使用两个嵌套的“While”循环来计算任何给定数字的两个因子,但仅在一次迭代之后,循环就停止了

计划

#include <iostream>
#include <conio.h>
using namespace std;
long int Password;

void main()
{ 
    long int n=2,n1=2;
    cout<<"Type the number whose factor you need"<<endl;
    cin>>Password;
    while( n <  3600 )
    { 
        while( n1 < 3600 )
        {
            if( n*n1 == Password )
            {
                cout<<"your Factors are "<<n<<" and "<<n1<<endl;
                getch();
            }
            else
            {
                n1++; 
                break;
            }
        }
        n++;
    }
}

输出仅适用于小数字,但当插入一些大数字时,程序终止。我不理解这个问题,因为代码非常好。是不是我的处理器不够强大?

【问题讨论】:

  • 这可以编译吗?始终使用大括号 - 防止错误
  • @EdHeal 是的,该程序在 VS 中构建并在 Turbo C++ 中编译
  • 如果条件满足,break;需要运行。
  • 对于 C++,它应该是 int main()
  • @Vinay5forPrime 这不是一个很好的问题。给出的代码和提出的问题之间几乎没有联系。我们最接近实际问题的是最后一句话,它似乎是凭空出现的,并且在问题的其他部分没有上下文。此外,您既没有表现出调试程序的任何努力,也没有询问如何调试它。

标签: c++ math while-loop nested-loops computation


【解决方案1】:

您的程序没有计算任何给定数字的因数。此外,将数字命名为“密码”会令人困惑。

也许你想要在 C++ 中这样的东西:

#include <iostream>

using namespace std;

int main() {
    unsigned int number;

    cout << "Enter a positive integer whose factors you need: " << endl;
    cin >> number;

    cout << "Factors of " << number << " are ";
    for (int i = 1; i <= number; ++i) {
        if (number % i == 0)
            cout << i << " ";
    }
    cout << endl;

   return 0;
}

正如 cmets 中所指出的,在 C++ 中你有 int main() 而不是 void main(),尽管有些编译器确实支持 void main()

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2017-11-14
    相关资源
    最近更新 更多