改正错误#include <iostream.h> int dec(int a[],int b[], int n, int m) { int c[50]; int s, h; int t=n>m?n:m; for (int i=0; i<=t; i++) { c[i]=a[i]+b[i]+c[i]; if (c[i]>=2) { c[i]=c[i]%2; c[i++]++; } } s=c[0], h; for( int j=0: j<i: j++) { h=h*2; s+=c[j]*h; return s; } void main ( ) { int a[50]={1,0,1,1,0,1,1,1,1}, b[50]={1,0,0,0,1,0,0,0,1,0,1,0,1}; int t=dec(a[50], b[50], 9,13); cout<<"相加之后十进制数为:"<<t<<endl; }
时间: 2023-11-27 08:54:46 浏览: 25
改正后的代码如下:
```c++
#include <iostream>
using namespace std;
int dec(int a[], int b[], int n, int m) {
int c[50] = {0}; // 注意初始化为0
int s = 0, h = 1; // 注意初始化 h 为1
int t = n > m ? n : m;
for (int i = 0; i <= t; i++) {
c[i] += a[i] + b[i];
if (c[i] >= 2) {
c[i] -= 2;
c[i + 1]++;
}
}
for (int j = 0; j <= t + 1; j++) {
s += c[j] * h;
h *= 2;
}
return s;
}
int main() {
int a[50] = {1, 0, 1, 1, 0, 1, 1, 1, 1};
int b[50] = {1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1};
int t = dec(a, b, 9, 12); // 注意传递的参数为数组名
cout << "相加之后十进制数为:" << t << endl;
return 0;
}
```
错误的地方有:
- `#include <iostream.h>` 应该改为 `#include <iostream>`。
- 函数 `dec` 中的 `c` 数组应该初始化为0,否则可能会出现意料之外的结果。
- 函数 `dec` 中的 `h` 变量应该初始化为1,在计算二进制转十进制时才能正确计算。
- 在函数 `dec` 中,最后一个循环的终止条件应该是 `j <= t + 1`,这样才能把最高位的进位也计算在内。
- 在主函数中调用 `dec` 函数时,应该传递数组名作为参数,而不是数组元素。
另外,上述代码中还有一个错误:函数 `dec` 的第一行应该加上返回值类型 `int`。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)