Sign-up....

请高手指我这段代码那里错了???

下面代码是要把二进制10111转换为十进制:

char * str = "10111";

int n = strlen(str);

int result;

for(int i = 0;i < n; i ++)

{

result += int(str[i]) * pow(2,n - i);

}

cout<<result;

运行后怎么显示结果为:

-858990438

[190 byte] By [msdn] at [2007-8-14 13:02:51]
# 1 Re: 请高手指我这段代码那里错了???

int result(0);//要初始化

yjm0105 at 2005-5-2 13:31:43 >
# 2 Re: 请高手指我这段代码那里错了???

int result = 0;

int result(0);

static int result;

都可以

bing_huo at 2005-5-2 13:34:54 >
# 3 Re: 请高手指我这段代码那里错了???

mark

yuhjnm_20001 at 2005-5-2 13:35:55 >
# 4 Re: 请高手指我这段代码那里错了???

初始化也不行啊

编译没问题,但结果不正确!!!

bg205 at 2005-5-2 13:38:08 >
# 5 Re: 请高手指我这段代码那里错了???

没有给result初值

result = 0;

useresu at 2005-5-2 13:39:02 >
# 6 Re: 请高手指我这段代码那里错了???

result没初始化。

zhousqy at 2005-5-2 13:39:49 >
# 7 Re: 请高手指我这段代码那里错了???

int(str[i]) 的到的是49,

1的ASCII值 ,

useresu at 2005-5-2 13:39:55 >
# 8 Re: 请高手指我这段代码那里错了???

不好意思,原来我以前贴的一段程序,

随便写上去的,

没调,

误导兄弟了

useresu at 2005-5-2 13:49:24 >
# 9 Re: 请高手指我这段代码那里错了???

#include<iostream>

#include <valarray>

using namespace std;

int main(){

char * str = "10111";

int n = strlen(str);

int result = 0; //给个初值

for(int i = 0;i < n; i ++)

{

result += (str[i]-48) * pow(2,n - i-1); //这里改一下,

}

cout<<result;

system("pause");

}

qhfu at 2005-5-2 14:19:57 >
# 10 Re: 请高手指我这段代码那里错了???

同意 qhfu(崩溃)

flfljh at 2005-5-2 14:45:28 >
# 11 Re: 请高手指我这段代码那里错了???
与楼上的结果一样……
Harvey_s at 2005-05-13 18:37:00 >

C/C++

All Classified