c++因子程序:输出给定因子数

C++ Factor Program: Outputting Number of Factors Given

本文关键字:输出 子程序 c++      更新时间:2023-10-16

我正在编写一个简单的程序,通过Linux重定向查找整数列表的因子。我快做完了,但有一部分卡住了。下面是我到目前为止的程序:

#include<iostream>
using namespace std;
int main()
{
int counter = 0;
int factor;
cin >> factor;
while (cin)
{
if (factor < 0)
break;
cout << "The factors of " << factor << " are " << endl;
for(int i=factor; i>=1; i--)
if (factor % i == 0)
  {
    counter++;
    cout << i << endl;
  }
cout << "There are " << " factors." << endl;
cout << endl;
cin >> factor;
}
return 0;
}

现在问题出在" cout <<"有"<<"因素"。& lt; & lt;endl;"。我不确定如何计算程序输出的因子数量。

例如:

7的因数是

1

7

有两个因素。

我该如何计算和输出这个例子中的"2"呢?

非常感谢帮助。

代替

cout << "There are " << " factors." << endl;
使用

cout << "There are " << counter << " factors." << endl;

如果你这样做,你必须移动你定义counter的那一行。

它不是main中的第一行,而是需要移动到while循环中的第一行。