为什么我从这个循环中获得此输出
Why I am getting this output from this loop?
#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。
相关文章:
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 而循环:简单的除法程序输出零,不明白为什么
- 为什么即使使用 for 循环遍历我的向量,它也没有输出到控制台?(C++)
- 如何在 c++ 中使用 for 循环输出矢量中的所有对象
- 我将如何保存此 for 循环的输出
- 该程序没有产生输出,而是卡在一个循环中,几秒钟后消失并打印被杀死?
- 循环C++不同的输出
- 在控制台上输出我从文件中读取的整数,将程序插入无限循环
- 创建一个循环,该循环将输出大于零且小于 60(不包括 60)的所有 5 的倍数
- 为什么当 while 循环中的 if 条件变为 false 时,我的函数不输出最后一条语句?
- 当输出达到某个值时,如何在 c++ 中中断计数器循环
- 尝试使用嵌套的 for 循环进行某些输出
- 循环内控制台中的输入和输出
- while 循环中的流输出文件() 通常生成空文件
- C++,程序输出无效输入,但继续通过循环
- 当我在循环内打印变量时无限输出
- 如何水平排列程序的打印输出循环而不重复