Two's complement in C++ - invalid types 'int[int]' for array subscript -
i'm trying implement sort of two's complement algorithm in c++ , far think logic correct. however, following error when run invalid types 'int[int]' 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}; (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; }
i guess purpose plus operation of 2 int arrays? little explanation: have declare 5 units 'c' there may 1 additional carrier (you called transmit)
#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}; (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; }
with format: array of decimal integers, hard converted binary directly. can still try give out solution:
// first convert unsigned int unsigned int result = 0; (int k = 0; k < 5; ++k) { result *= 10; result += c[k]; } // convert binary char binary[32]; // 32bit should enough int len = 0; while (result > 0) { binary[len++] = (result % 2) + '0'; result /= 2; } // print binary (int k = len - 1; k >= 0; --k) { printf("%c", binary[k]); }
the full program:
#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}; (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 unsigned int unsigned int result = 0; (int k = 0; k < 5; ++k) { result *= 10; result += c[k]; } // convert binary char binary[32]; // 32bit should enough int len = 0; while (result > 0) { binary[len++] = (result % 2) + '0'; result /= 2; } // print binary (int k = len - 1; k >= 0; --k) { printf("%c", binary[k]); } printf("\n"); return 0; }
Comments
Post a Comment