for 循环未运行,尝试向后迭代数组元素
for loop not running, trying to iterate backwards through array elements
为了练习使用指针和数组,我正在尝试做一个简单的程序,能够将二进制输入转换为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
}
- 数组元素打印的递归方法
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- 迭代一组和擦除元素
- 用std :: apply迭代元组元素
- 使用boost multiarray迭代器在数组元素之间进行赋值