为什么我从这个循环中获得此输出

Why I am getting this output from this loop?

本文关键字:输出 循环 为什么      更新时间:2023-10-16
#include <iostream>
using namespace std;

我是CPP和编程的新手,我正在尝试找到一个数字的因素,max,为什么我的代码输出以其方式出现?

int max;
cout << "Enter a number you'd like to see the divisors of: " << endl;
cin >> max;
//I am trying to find all divisors for the number max
//I know this isn't the most efficienct way but I thought that it would work.
//Instead of 50, 25, 20, 10, 5 ,1 for output it looks like 50, 25, 25, 25 25, 5 
for (int t=1; t <= max; t++) {
  if (max % t == 0) {
    int m = max/t; 
  }
} 
cout << m << endl;

您的输出放错了位置。将cout << m << endl;语句移至您的if语句块:

if (max % t == 0) { // start of a block
    int m = max / t;
    std::cout << m << 'n';
} // end of a block

确保使用括号{}正确标记语句块。现在,对于 50 的给定输入,输出为:

50 25 10 5 2 1

coliru上的现场示例

using namespace std;

正如Bo41所说,您绝不应该使用命名空间,这是一些原因:为什么使用"使用命名空间std"被认为不良习惯?

而不是使用命名空间,而应仅编写您使用的内容,例如:

using std::cout;
using std::endl;

现在回到一个问题:

for(int t=1; t <= max; t++){
    if(max % t == 0)
        int m = max/t; 
} cout << m << endl;

请注意,您在IF内部定义M并在其外部使用它。另外,如果不是那样,您将仅打印出您找到的最后一个除数。您应该做更多类似的事情:

for(int t = 0; t <= max; t++){
    if(max % t == 0){
        int m = max/t
        cout << m << endl;
    }
}

在这里您将打印Max的每个除数。就我个人而言,即使在街区中只有一行,我总是会为if语句打开一个块,对我而言,它的井井有条,可能会阻止错误。

这是您的整个程序吗?变量

int m

在线路上超出范围

cout << m << endl;

这使我相信您有一个名为" M"的变量,该变量在该程序中较早声明了,该变量被新声明的INT遮蔽了Inf block中的" M"。如果是这种情况,则先前声明为if-block之外的变量" M"将被打印到COUT。