简体   繁体   English

如何计算一个循环执行了多少次?

[英]how to count how many times a loop was executed?

I am writing a program that prints products of a number, (for example, 2 can be 1 * 4, 2 * 2, 4 * 1 and counter shows (3) numbers), I need to have a counter that counts how many numbers were printed.我正在编写一个打印数字乘积的程序,(例如,2 可以是 1 * 4、2 * 2、4 * 1 和计数器显示(3)个数字),我需要一个计数器来计算多少个数字被打印了。 I can't use (i) as a counter as it counts everything.我不能使用 (i) 作为计数器,因为它会计算所有内容。

for(i=1; i<=number; i++)
{
    if(number%i==0)
    cout<<i<<"*"<<number/i<<"="<<number<<endl;
}
return 0;

Just add another variable and expand the body of the if-statement right?只需添加另一个变量并扩展 if 语句的主体,对吗?

int count = 0;
for(i=1; i<=number; i++)
{
  if(number%i==0) {
    cout<<i<<"*"<<number/i<<"="<<number<<endl;
    count++;
  }
}
cout << "Printed " << count << " times" << endl;
return 0;

Because i is declared outside of the loop, gets initialized to 1, and is already incremented by 1 each iteration, you can just print it out after.因为i是在循环之外声明的,被初始化为 1,并且每次迭代都已经递增 1,所以您可以在之后将其打印出来。

int i;
for(i=1; i<=number; i++)
{
    if(number%i==0)
    cout<<i<<"*"<<number/i<<"="<<number<<endl;
}
cout << "Looped " << i << " times\n";
return 0;

Just note i must be declared outside the loop.请注意, i必须在循环之外声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM