在c++中,循环后无法改变整数的值

unable to change value of integer after looping, C++

本文关键字:改变 整数 c++ 循环      更新时间:2023-10-16

在程序开始时,我声明了变量ij

int i, j;

在执行过程中,我也使用变量名ij作为oop索引变量。我意识到这可能不是清晰的最佳选择,但由于这是一个玩具项目,我认为这无关紧要。

问题是,在将数组的内容打印到txt文件的循环之后,i == N == 29:

ofstream a_file("2d_array.txt");
for (int i = 0; i<N; ++i) {
  for (int j = 0; j<N; ++j)
    a_file << m[i][j] << ' ';
    a_file << endl;
}

当我试图在程序中再次使用i:

for (int num_slices_processed = h + 1; num_slices_processed < N;
         num_slices_processed++){
  i = 0;
  j = num_slices_processed;
  ...

i仍然设置为29,即使在应该设置为0的行之后。j设置正确。这里发生了什么?


以下是问题部分的所有代码:

#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int smallest(int x, int y, int z);
bool basesMatch(char b1, char b2);
int main() {
    const int N = 29;
    int h, l, mm;
    int i, j;
    l = 10;
    mm = 2;
    h = 5;
    int m[N][N];
    //initialize m
    for (int i = 0; i < N; i++){
        for (int j = i; j < N; j++) {
            if (j-i <= h)
                m[i][j] = 0;
        }
    }
    ofstream a_file("2d_array.txt");
    for (int i = 0; i<N; ++i) {
        for (int j = 0; j<N; ++j)
            a_file << m[i][j] << ' ';
        a_file << endl;
    }
    for (int num_slices_processed = h + 1; num_slices_processed < N; num_slices_processed++){
        //while j is in bounds, ie j < N. This fills in one diagonal slice of m from L->R top -> bottom.
        i = 0; //************ i is not being set here
        j = num_slices_processed;
        while (j < N) {
            if (basesMatch(seq[i], seq[j])) {
                t = m[i + 1][j - 1];
                m[i][j] = m[i + 1][j - 1];
            }
            else  {//bases don't match
                m[i][j] = smallest(m[i + 1][j] + 1, m[i][j - 1] + 1, m[i + 1][j - 1] + 1);
            }
            i++;
            j++;
        }
    }

检查它是否进入循环。Num_slices_processed可以是null或者已经是<N,所以你永远不会碰到赋值语句>