【问题标题】:Simple program crashes for some reason简单的程序由于某种原因崩溃
【发布时间】:2015-08-05 13:08:21
【问题描述】:

我写了一个简单的二进制计算器,我将要开发它。第一次计算时一切正常,但之后程序崩溃-“Binary.exe 已停止工作”。我认为动态可能有问题在函数“decToBin()”中分配了数组,但我无法发现问题。代码如下:

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

    using namespace std;

    void binToDec()
    {
    string bin;
    cout<<"Binary code: ";
    cin>>bin;

    int powr = 0;
    int num = 0;
    long long sum = 0;


    for(int i=bin.size()-1; i>=0; i--)
    {
        if(bin[i] == '1')
        {
            num = 2;
        }
        else if(bin[i] == '0')
        {
            num = 0 ;
        }
        sum += pow(num,powr);
        cout<<sum<<endl;

        powr++;
    }
    cout<<"Decimal: "<<sum<<endl;

    sum = 0;
    powr = 0;
    num = 0;
}

void decToBin()
{
    int dec = 0;
    cout<<"Decimal number or digit: ";
    cin>>dec;

    int i = 0;
    int *numBin = new int[i];
    while(dec > 0)
    {
        numBin[i] = dec%2;
        dec = dec/2;
        i++;
    }
    cout<<"Binary: ";
    for(int j = i-1; j>=0; j--)
    {
        cout<<numBin[j];
    }
    cout<<"\n";
    i = 0;
    delete [] numBin;
}

int main()
{
    //USER INPUT
    int nav = 0;


    while(true)
    {
        cout<<"\n";
        cout << "1.Binary to decimal:"<<endl;
        cout << "2.Decimal to binary:"<<endl;
        cin>>nav;

        switch(nav)
        {
        case 1:
        {
            binToDec();
            break;
        }
        case 2:
        {
            decToBin();
            break;
        }
        }

    }
    return 0;
}

【问题讨论】:

  • decToBin() 有问题。 numBin 的大小为 0,但您向其添加元素。为什么不使用任何 STL 容器呢?还有为什么math.h 和conio.h?
  • int i = 0; int *numBin = new int[i]; 可能不是您想要的。因为循环中的行numBin[i] = dec%2; 是UB。
  • 我可以使用什么 STL 容器?math.h 用于 pow()。
  • @figorix 这是 C++,所以除了原始数组。从向量开始。
  • 您一定是在开玩笑,使用power 函数将二进制转换为十进制。研究您最喜欢的关于“位移”和“二进制与”(屏蔽)的参考资料。

标签: c++ crash calculator


【解决方案1】:

你的问题:

int *numBin = new int[i]; //i is 0, then you add elements to it

一个简单的解决方案,使用std::vector:

vector<int> numBin;
...
numBin.push_back(dec%2);

您现在完全不必担心动态内存。

【讨论】:

  • 但是在 for 循环中我必须使用 vector::iterator 对吗?
  • @figorix,向量的大小不自动增加,可以一起取出i。
猜你喜欢
  • 1970-01-01
  • 2016-05-10
  • 2012-01-24
  • 2022-07-24
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 2021-06-04
相关资源
最近更新 更多