简体   繁体   English

使用数组减去数字 - C ++

[英]Subtract numbers using arrays - C++

I want to calculate the difference between two numbers (let's say v and n , so vn ) using arrays (don't ask why I have to do so). 我想用数组来计算两个数字之间的差异(比方说vn ,所以vn )(不要问为什么我必须这样做)。 The arrays for each number are made in the following way: 每个数字的数组按以下方式进行:

  • Their capacity is the number of digits of the greatest number between v and n (= q in the code) 它们的容量是vn之间最大数字的位数(代码中的q
  • vArray[i] = i th digit of v except leading zeros to fill the whole array vArray[i] = vi个数字,除了前导零以填充整个数组
  • nArray[i] = - i th digit of n except leading zeros to fill the whole array nArray[i] = - i TH的数字n除了前导零填充整个阵列

For example, choose v = 10 and n = 2 then, 例如,选择v = 10和n = 2,然后,

vArray = [1,0]
nArray = [0,-2]

So I wrote this code to calculate the sum array that will be equal to the digits of the difference ( sum = [0,9] for the example above): 所以我编写了这段代码来计算sum数组,它将等于差值的数字(上面例子中sum = [0,9] ):

long r = 0;
for (int i = q-1 ; i > -1; i--){
    sum[i] = vArray[i] + nArray[i];
    if (sum[i] < 0){
        r = floor(sum[i]/10);
        sum[i-1] -= r;
        sum[i] = sum[i]+10;
    }else{
        r = 0;
    }

    NSLog(@"%li",sum[i]);
}

The problem is that sum array isn't equal to what it should be. 问题是sum数组不等于它应该是什么。 For the same example, sum = [1,8] What is the problem in the code? 对于同一个例子, sum = [1,8]代码中的问题是什么?

note : vArray and nArray are properly generated. 注意:正确生成了vArraynArray

EDIT : A few examples and expected results 编辑:一些例子和预期的结果

    v =  |    n =   |  vArray =   |     nArray=    |    sum=
    25   |    9     |    [2,5]    |      [0,9]     |    [1,6]
    105  |    10    |   [1,0,5]   |     [0,1,0]    |   [0,9,5]
   1956  |   132    |  [1,9,5,6]  |    [0,1,3,2]   |  [1,8,2,4]
  369375 |   6593   |[3,6,9,3,7,5]|  [0,0,6,5,9,3] |[3,6,2,7,8,2]

I believe I understand the data structure, as you are using a Big Integer representation. 我相信我理解数据结构,因为您正在使用Big Integer表示。

Given the number: 1234 鉴于数量:1234

Your V array is: [1, 2, 3, 4]. 你的V阵列是:[1,2,3,4]。

To add all the digits (aka sum), which I don't see why you want to do this, is: 要添加所有数字(也就是总和),我不明白为什么要这样做,是:

int digit_sum = 0;
for (int i = 0;  i < 4; i++)
{
    digit_sum += v[i];
} 

To convert the representation into "normal", try this: 要将表示转换为“正常”,请尝试以下操作:

int value = 0;
for (int i = 0; i < 4; ++i)
{
  value = (value * 10) + v[i];
}

To perform a subtraction, you will have to perform the steps as if you doing this by hand. 要执行减法,您必须执行这些步骤,就像您手动执行此操作一样。 Also, you would need a second number too. 此外,您还需要第二个号码。

Edit 1: link to big number subtraction 编辑1:链接到大数减法
This might help: 这可能有所帮助:
Big Number Subtraction in C C中的大数减法
C++ Large Number Arithmetic C ++大数字算术

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM