数组的加法和减法

时间:2014-10-30 00:13:28

标签: c++ arrays addition

我整天都在努力,但却无法正确输出。 我想要做的是输入两个数字,这些数字将被推入两个数组,因此我们可以减去或添加它们并显示结果。看似简单,但捕获量很少

  1. 输入必须从用户逐个推入阵列。
  2. 如果我没有输入值,代码应该将其视为'0''null''0'如果它在开头,'null'如果它在最后。例如,如果第一个数字是234而第二个数字是23,那么代码应该进入'023',如果我输入第一个数字为2,则第二个数字为3但是不要在最后输入任何内容,然后代码应该假定它是null
  3. 问题

    1. 我不能带着'如果总和大于10,则转到下一组。这意味着我得到的值只是添加两个数字并不重要,如果它大于10。例如,添加234890会给我[10, 12, 4]
    2. 这是代码.....

      #include<iostream>
      using namespace std;
      
      main() {
          int first[10], second[10], result[10], c, n;
      
          cout << "Enter the number of elements in the array ";
          cin >> n;
          if (n > 10 || n < 0) {
              std::cout << "invalid number, you are a bad reader" << endl;
              system("PAUSE");
              return 0;
          }
      
          cout << "Enter elements of first array " << endl;
      
          for (c = 0; c < n; c++) {
              cin >> first[c];
              if (first[c] > 9 || first[c] < 0) {
                  std::cout << "invalid number, you are a bad reader" << endl;
                  system("PAUSE");
                  return 0;
              }
      
          }
          cout << "Enter elements of second array " << endl;
      
          for (c = 0; c < n; c++)
              cin >> second[c];
      
          cout << "Sum of elements of two arrays " << endl;
      
          for (c = 0; c < n; c++)
              cout << first[c] + second[c] << endl;
      
          if ((first[c] + second[c]) > 9) {
              cout << "overflow" << endl;
          }
      
          //result[c] = first[c] + second [c];
          //cout << result[c] <<endl;
          system("PAUSE");
          return 0;
      }
      

      我真的很感激一些建议。

2 个答案:

答案 0 :(得分:1)

如果您打算获得例如

的结果
234 + 890 = 1124

那么你的求和循环应该是相反的顺序。 (由于您正在从提示中读取数组的元素数量,因此您可以使用此信息按照以下求和循环的首选顺序将第一个/第二个数字输入到每个数组中。)

对于进位问题,你需要设置一个变量并在循环中使用它,例如。

int sum[10] = {0};
int c;

int carry = 0;
for (c = 0; c < n; c++)
{
    sum[c] = first[c] + second[c] + carry;
    carry = sum[c] / 10;
}
if (c < n)
    sum[c] = carry;
else
    cout << "overflow";

答案 1 :(得分:0)

使用std :: vector并学习如何使用反向迭代器。因此,如果某人输入234,则推送push_back(2),push_back(3),push_back(4)并且[0] = 2,[1] = 3,[2] = 4。然后,如果下一个数字是23,则[0] = 2,[1] = 3。现在使用反向迭代器遍历两个向量,因此第一次调用rbegin()将给出指向[2] = 4的指针,而另一个向量将给出[1] = 3。现在使用push_back添加并携带到第三个向量中以存储结果。使用反向迭代器输出结果以打印结果。

这看起来像家庭作业,所以没有示例代码。

相关问题