如何忽略/删除前导零? [英] How to ignore/remove leading zeros?

查看:118
本文介绍了如何忽略/删除前导零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个在C中添加两个大数字的程序. 我的整数数组结果包含两个数字的和(它们也存储在数组中).

I am writing a program to add two large numbers in C. My integer array result holds the sum of the two numbers (which were also stored in arrays).

例如,如果结果数组为[0,0,3,2](实际数组大小为20)

For example, if the result array is [0,0,3,2] (actual array size is 20)

如果我的实际结果是32,如何显示结果数组的内容而没有前导零?

If 32 is my actual result, how can I display the contents of the result array without the leading zeros ?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BASE 10
void align(int A[],int n);
void add(int A[],int B[], int C[]);
void Invert(int* a, int n);

int main(int argc, char** argv){
    char input1[20];
    char input2[20];
    int size = 20;
    int a;
    int b;
    int num1[20];
    int num2[20];
    int result[20];
    int length1 = strlen(argv[1]);
    int length2 = strlen(argv[2]);
    int i = 0;
    for (i=0;i<length1;i++){
       input1[i] = argv[1][i];
    }
    for (i=0;i<length2;i++){
        input2[i] = argv[2][i];
    }

    a=atoi(input1);
    b=atoi(input2);
    align(num1,a);
    align(num2,b);
    add(num1,num2,result);
    Invert(result,size);
    for (i=0;i<20;i++){
        printf("%d",result[i]);
    }

    return 0;
}

void align (int A[], int n){
    int i = 0;

    while (n) {
        A[i++] = n % BASE;

        n /= BASE;
    }

    while (i < 20) A[i++] = 0;
}

void add (int A[], int B[], int C[]) {
    int i, carry, sum;
    carry = 0;
    for (i=0; i<20; i++) {
        sum = A[i] + B[i] + carry;
        if (sum >= BASE) {
            carry = 1;
            sum -= BASE;
        } else
            carry = 0;
        C[i] = sum;
    }

    if (carry) printf ("overflow in addition!\n");
}

void Invert(int* a, int n)
{
    int i;
    int b;
    for(i=0; i<n/2; i++){
        b = a[i];
        a[i] = a[n-i-1];
        a[n-i-1] = b;
    } 
}

`

推荐答案

要获取实际的数字(我假设每个数字都以字节的形式存储在20字节的数组中,最低的数字在最高的索引处),您可以执行一些操作像这样:

To get the actual digits (I assume that each digit is stored as a byte in an array of 20 bytes, lowest digit at highest index), you do something like this:

int i;
int size = sizeof(thearray) / sizeof(thearray[0]);

/* find first non-0 byte, starting at the highest "digit" */
for (i = 0; i < size - 1; ++i)
    if (thearray[i] != 0)
        break;

/* output every byte as character */
for (; i < size; i++)
    printf("%c", thearray[i] + '0'); /* 0 --> '0', 1 --> '1', etc. */
printf("\n");

这篇关于如何忽略/删除前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆