jeudi 28 juillet 2016

General large input test. Hexadecimal arrays in C++11

Almost all my input parameters work except for some larger number inputs for my hexadecimal addition program. My program asks user to input two numbers and it would give out the sum of the two numbers. However, the number should be only 10 digits long, and if it exceeds 10 digits it should output an Addition Overflow.

  1. If I input "1" for first number and "ffffffffff" (10 digits) for my second number I would get an output of "Addition Overflow.". (Correct)
  2. However, if my first number were to be a "0" and second number to still be "ffffffffff" I would get an "Addition Overflow." which is incorrect. The output should still be "ffffffffff"

Here is my code:

#include <iostream>

using namespace std;

bool add(char[], int, char[], int, char[], int);
int getvalue(char);

int main(){
  const int length = 10;
  char first_num[length], second_num[length], answer[length+1], yorn;
  bool over;
  int d1, d2;

  cout << "Enter first number:" << endl;
  cin >> first_num;
  cout << "Enter second number:" << endl;
  cin >> second_num;

  for(d1 = 0; first_num[d1] != '\0'; d1++)
    first_num[d1] = tolower(first_num[d1]);
  for(d2 = 0; second_num[d2] !='\0'; d2++)
    second_num[d2] = tolower(second_num[d2]);

  if (d2 < d1)
    over = add(first_num, d1, second_num, d2, answer, length);
  else
    over = add(second_num, d2, first_num, d1, answer, length);
  if(over)
    cout << "Addition Overflow." << endl;
  else
    cout << "The sum is " << answer << "." << endl;

  return 0;
}

int getvalue(char h){
  char hex[17] = {"0123456789abcdef"};
  for (int i = 0; i < 17; i++)
    if(h == hex[i])
return i;
}
bool add(char second_num[], int m, char first_num[], int l, char answer[], int length){
  char hex[17] = {"0123456789abcdef"};
  int digits = 0, a, c = 0, i;
  for (i = 0; i < length+1; i++)
    answer[i] = '\0';
  l--;
  m--;
  while (l >= 0){
    a = getvalue(second_num[m]) + getvalue(first_num[l]) + c;
    c = a/16;
    answer[m] = hex[a%16];
    m--;
    l--;
     digits++;
  }
  while (m >= 0){
    a = getvalue(second_num[m]) + c;
    c = a/16;
    answer[m] = hex[a%16];
    m--;
    digits++;
  }
  if (c != 0){
    for(i = digits; i >= 0; i--)
      answer[i] = answer[i-1];
    answer[0] = hex[c];
  }
  if(digits > length - 1)
    return true;
  return false;
}

Aucun commentaire:

Enregistrer un commentaire