我试图用C ++实现某种二进制补码算法,到目前为止我认为我的逻辑是正确的。但是,当我运行invalid types 'int[int]' for array subscript
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
int a[4] = {0, 2, 3, 5};
int b[4] = {9, 7, 8 ,4};
int sum = 0;
int transmit = 0;
int c{0};
for (int k=3;k>0;k--){
sum = a[k]+b[k]+transmit;
c[k+1]=sum%10;
transmit=sum/10;
}
c[0] = transmit;
return 0;
}
答案 0 :(得分:4)
c
的类型为int
int c{0};
你试图取消引用它,好像它是一个数组:
c[k+1]=sum%10;
您无法合法取消引用int
。
答案 1 :(得分:0)
我猜你的目的是做两个int数组的加操作? 一个小解释:你必须为'c'声明五个单位,因为可能有一个额外的载体(你称为传输)
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
int a[4] = {0, 2, 3, 5};
int b[4] = {9, 7, 8 ,4};
int sum = 0;
int transmit = 0;
int c[5] = {0};
for (int k=3;k>0;k--){
sum = a[k]+b[k]+transmit;
c[k+1]=sum%10;
transmit=sum/10;
}
c[0] = transmit;
return 0;
}
使用这种格式:十进制整数数组,它们有点难以直接转换为二进制。但我仍然可以尝试提出解决方案:
// first convert to an unsigned int
unsigned int result = 0;
for (int k = 0; k < 5; ++k) {
result *= 10;
result += c[k];
}
// then convert to binary
char binary[32]; // 32bit should be enough
int len = 0;
while (result > 0) {
binary[len++] = (result % 2) + '0';
result /= 2;
}
// finally print binary
for (int k = len - 1; k >= 0; --k) {
printf("%c", binary[k]);
}
完整的计划:
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
int a[4] = {0, 2, 3, 5};
int b[4] = {9, 7, 8 ,4};
int sum = 0;
int transmit = 0;
int c[5] = {0};
for (int k=3;k>0;k--){
sum = a[k]+b[k]+transmit;
c[k+1]=sum%10;
transmit=sum/10;
}
c[0] = transmit;
// first convert to an unsigned int
unsigned int result = 0;
for (int k = 0; k < 5; ++k) {
result *= 10;
result += c[k];
}
// then convert to binary
char binary[32]; // 32bit should be enough
int len = 0;
while (result > 0) {
binary[len++] = (result % 2) + '0';
result /= 2;
}
// finally print binary
for (int k = len - 1; k >= 0; --k) {
printf("%c", binary[k]);
}
printf("\n");
return 0;
}