程序成功运行所需的 C++ 外来 for 循环

标签 c++ loops binary

在我们开始之前,是的,这是家庭作业,不,我不是要让其他人来做我的家庭作业。我遇到了一个问题,让某人输入最多 7 位的二进制数,然后将该数字从二进制更改为十进制。虽然我肯定没有使用最有效/最好的方法,但我相信我可以让它发挥作用。让我们看一下代码:

#include <iostream>
#include <math.h>

using namespace std;

int main() {
    char numbers[8];
    int number = 0, error = 0;

    cout << "Please input a binary number (up to 7 digits)\nBinary: ";

    cin.get(numbers, 8);
    cin.ignore(80, '\n');

    for (int z = 7; z >= 0; z--){}
    cout << "\n";

    for (int i = 0, x = 7; x >= 0; x--, i++){
        if (numbers[x] <= 0){ // if that is an empty space in the array.
            i--;
        }
        else if (numbers[x] == '1'){
            number += pow(2, i);
        }
        else if (numbers[x] != '0'){ // if something other than a 0, 1, or empty space is in the array.
            error = 1;
            x = -1;
        }
    }
    if (error){ // if a char other than 0 or 1 was input this should print.
        cout << "That isn't a binary number.\n";
    }
    else{
        cout << numbers << " is " << number << " in decimal.\n";
    }
    return 0;
}

如果我运行这段代码,它会完美运行。然而,快速浏览一下代码,就会发现这个“for (int z = 7; z >= 0; z--){}”似乎什么也没做。但是,如果我将其删除或注释掉,我的程序会认为任何输入都不是二进制数。如果有人能告诉我为什么需要这个循环和/或如何删除它,将不胜感激。谢谢:)

最佳答案

在你的循环中:

for (int i = 0, x = 7; x >= 0; x--, i++){
    if (numbers[x] <= 0){ // reads numbers[7] the first time around, but
                          // what if numbers[7] hasn't been set?
        i--;
    }

如果输入的长度少于七个字符,您可能会读取一个未初始化的值。这是因为 numbers 数组未初始化,cin.get 仅在字符串的最后一个字符之后放置一个空终止符,而不是整个数组的其余部分。一种简单的修复方法是初始化数组:

char numbers[8] = {};

至于为什么外来循环会修复它——读取未初始化的值是未定义的行为,这意味着无法保证程序将执行的操作。

关于程序成功运行所需的 C++ 外来 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25702236/

相关文章:

c++ - 用于创建 integral_constants 的任意元组的通用实用程序

c++ - 如何使用来自boost的模板相关信号成员实现模板类?

c - 为什么 Fread 以相反的顺序读取 unsigned-int?

c++ - 如何在 C++ 中正确地从 ROS 发送数组?

python - 遍历列表并尝试删除 ('\n' 时,列表返回 None 而不是列表的元素

使用循环变量条件的 C 循环优化

json - 如何在 Haxe 中迭代动态对象

binary - 65和二进制中的字母A有什么区别?

mysql - 以二进制形式插入和选择 UUID(16)

c++ - BFS遍历图节点两次