简单程序由于某种原因崩溃
Simple program crashes for some reason
我写了一个简单的二进制计算器,我打算 develop.Everything 进行一些初步计算,但之后程序崩溃了-"Binary.exe has stopped working"。我认为可能有问题函数 "decToBin()" 中的动态分配数组,但我无法识别 issue.Here 的代码:
#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;
}
您的问题:
int *numBin = new int[i]; //i is 0, then you add elements to it
一个简单的解决方案,使用 std::vector
:
vector<int> numBin;
...
numBin.push_back(dec%2);
你现在完全不用担心动态内存了。
我写了一个简单的二进制计算器,我打算 develop.Everything 进行一些初步计算,但之后程序崩溃了-"Binary.exe has stopped working"。我认为可能有问题函数 "decToBin()" 中的动态分配数组,但我无法识别 issue.Here 的代码:
#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;
}
您的问题:
int *numBin = new int[i]; //i is 0, then you add elements to it
一个简单的解决方案,使用 std::vector
:
vector<int> numBin;
...
numBin.push_back(dec%2);
你现在完全不用担心动态内存了。