简体   繁体   English

如何使用“while 循环”打印正确的 output?

[英]How to print the Correct output using “ while loop ”?

The Expected Output is 2000 but it stops on 1980.预期的 Output 是 2000,但它在 1980 停止。

Note: The Execution is started from 20 and not from 0 as int i = 1注意:执行从20开始,而不是从0开始,因为int i = 1

The Code:编码:

#include <iostream>
using namespace std;
int main() {
  const int iarraysize = 100;
  int i = 1;
  int iarray[iarraysize];
  while (i < iarraysize) {
    iarray[i] = 20 * i;
    cout << iarray[i++] << "\n";
  }
}

Arrays start at 0, and end one before their size. Arrays 从 0 开始,在它们的大小之前结束 1。

You don't need an array however.但是,您不需要数组。

#include <iostream>
int main()
{
    int limit = 100;
    int i = 1;
    while (i <= limit)
    {
        std::cout << (i++ * 20) << "\n";
    }
}

The array goes from 0 to 99, you start at 1 and it only goes to 99 (99*20=1980).数组从 0 到 99,从 1 开始,它只到 99 (99*20=1980)。

You're expecting 2000 but there's no iarray[100] (array out of bounds).您期待 2000 但没有iarray[100] (数组越界)。

The last value of the variable i that is less than 100 is 99. So 20 * 99 is equal to 1990 .变量i的最后一个小于 100 的值是 99。所以 20 * 99 等于1990

If you want to get 2000 then rewrite the loop like如果你想得到 2000 然后重写循环

int i = 0;
while (i < iarraysize) {
  iarray[i] = 20 * (i + 1);
  cout << iarray[i++] << "\n";
}

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

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