【问题标题】:Loop terminates after fourth iteration循环在第四次迭代后终止
【发布时间】:2020-06-13 06:14:55
【问题描述】:

这是我的代码

#include<iostream>
#include<cmath>
using namespace std;
#define ll long long
int main()
{
    ll int a;cin>>a;
    ll int i=1;
    ll int arr[i];
    while(a)
    {
        arr[i-1]=a%10;
        a/=10;
        i++;
        cout<<a<<" ";
    }
    i--;
    cout<<endl;
    cout<<i<<endl;
}

我得到的输出为

>12345 1234 123 0 
>4

输入:

123456

循环在第四次迭代后终止,即使 while 条件不满足。谁能指导我?

【问题讨论】:

  • arr 有点小
  • arr 大小为 1 btw
  • 这个项目的目标是什么?
  • 你确定这段代码可以编译吗?数组的大小应该在编译时固定。 “arr[i-1]=a%10;”肯定会导致超出范围的问题。
  • 可能只是在每个循环中打印所有变量中的值——您将看到代码是如何工作的。或者学习如何使用调试器。

标签: c++ loops while-loop c++14


【解决方案1】:

首先给定的代码由于以下语句而无法编译

ll int arr[i];

将 i 更改为如下所示的某个常数值

ll int arr[1];

然后它将迭代循环 6 次并给出以下结果

输入: 123456

输出:

12345 1234 123 12 1 0

6

【讨论】:

  • arr[1] 会因为 arr 大小为 1 导致访问冲突而导致程序崩溃