for 循环未运行,尝试向后迭代数组元素

for loop not running, trying to iterate backwards through array elements

本文关键字:迭代 数组元素 循环 运行 for      更新时间:2023-10-16

为了练习使用指针和数组,我正在尝试做一个简单的程序,能够将二进制输入转换为denary.. 我想我对逻辑有一个好主意,但我什至还没有尝试实现它,因为我正在努力让我的 for 循环运行!

这看起来很愚蠢,但我知道 for 循环中的代码在它之外工作正常,所以它一定是条件有问题..? 我试图从 char 数组的后面开始(使用指针导航(并将每个字符(作为整数(输出到第一个元素。

所以所需的输出是"0 - 1 - 0 - 1 -">

#include <iostream>
using std::cout;
using std::endl;
//prototypes
void binaryToDenary(const char* input, int& inputLength);
int main(){
    const char binaryInput[] = {1,0,1,0};
    int inputLength = sizeof(binaryInput)/sizeof(binaryInput[0]);
    binaryToDenary(binaryInput, inputLength);
    return 0;
}
void binaryToDenary(const char* input, int& inputLength){
    //testing some stuff--- this all works as expected
    //cout << input[2] << " " << (int)*(input+2) << " " << inputLength <<endl;
    int i;
    for(i = inputLength; i < 0; i--){
        cout << (int)*(input+i) << " - ";
    }
}

你的for循环应该是这样的:

for(i = inputLength -1 ; i  >= 0; i--)
{
    cout << (int)*(input+i) << " - ";
}

代码中存在两个问题:

  • i = inputLength应该i = inputLength -1
  • i < 0应该i >= 0

此外,将第二个参数类型从 int & 更改为 int

void binaryToDenary(const char* input, int inputLength) //now its better!

int&类型减少了用例,几乎没有任何好处。如果使用 int & ,那么所有这些都会给出编译错误:

const int inputLength = sizeof(binaryInput)/sizeof(binaryInput[0]);
^^^^ note this
binaryToDenary(binaryInput, inputLength); //compilation error
binaryToDenary(binaryInput, sizeof(binaryInput)/sizeof(binaryInput[0])); //error
binaryToDenary(binaryInput, 4); ////compilation error

所以使用 int ,以上所有内容都可以编译!

数组索引从零开始,所以最后一个元素位于 inputLength - 1 处。有了i < 0你就会立即退出循环,因为这永远不会是真的......

for(i = inputLength - 1; i >= 0; i--){
    cout << (int)*(input+i) << " - ";
}
for(i = inputLength; i < 0; i--)

只有在输入长度小于 0 时才运行,这是不可能的?

你需要:

for(i = (inputLength-1); i >= 0; i--)
         ^^^^^^^^^^^^^^    ^^

C 数组从 0 开始,因此有效索引由下式给出

(0 <= i) && (i < array_length)

在您的程序中,这意味着初始化中最后一个数字的位置应该inputLength - 1,循环条件应该i >= 0

(至于为什么你循环没有运行,一开始你就i == inputLength了,所以我是肯定的,立即不符合i < 0条件(。

只要

i大于(或可能等于(为零,您就可以运行。只要i小于零,您就尝试运行循环,并且从大于零的值开始会导致您永远不会进入循环。

for(i = inputLength; i > 0; i--){
        cout << (int)*(input+i) << " - ";
}

您必须检查迭代循环变量i是否为正值。

但是,您应该在二进制输入向量上使用 STL 迭代器,而不是以 c 方式循环其内容,如果您想练习C++,可能的解决方案可能是:

vector<char> binaryInput;
binaryInput.push_back(1);
binaryInput.push_back(0);
binaryInput.push_back(1);
binaryInput.push_back(0);
vector<char>::iterator it;
for ( it=myvector.begin() ; it < myvector.end(); it++ ){
    cout << " " << *it << endl; //or whatever you need to do with vector content
}