增量和减少数组 - 用我的代码......需要另一个解决方案 [英] increment & decrement array - with my code..need another solution

查看:59
本文介绍了增量和减少数组 - 用我的代码......需要另一个解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果数组输入:1 0 0 0

递增数组应为:1 0 0 1

递减数组:0 9 9 9



i使用标签和循环来完成这项任务。但在背诵它时似乎很复杂。所以我需要知道是否有任何简单的方法来解决这个程序。如果是这样帮助我。

这是我的代码。



if array input: 1 0 0 0
incremented array should be:1 0 0 1
decremented array: 0 9 9 9

i have used label and loop to complete this task. but it seems complex in reciting it. so i need to know is there any simple method to solve this program. if so help me.
here is my code.

#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],b[20],c[20],n,i,j;
clrscr();
printf("\n Enter the no of elemnts");
scanf("%d",&n);
printf("\n enter the array\t");
for(i=0;i<n;i++)>
scanf("%d",&a[i]);
for(i=0;i<n;i++)>
c[i]=a[i];
j=n;
check:
if((a[j-1]+1)<=9)
a[j-1]++;
else
{
a[j-1]=0;
j--;
goto check;
}
if(a[0]==0)
{
for(i=1,j=0;i<=n;i++,j++)
b[i]=a[j];
b[0]=1;
printf("result of incremnted array\t");
for(i=0;i<=n;i++)
printf("%d\t",b[i]);
}
else
{
printf("result of incremnted array\t");
for(i=0;i<n;i++)>
printf("%d\t",a[i]);
}
j=n;
while(j>=0)
{
if(c[j-1]==0)
 {
if(c[j-2]==0)
j=j-1;
else
{
c[j-2]--;
c[j-1]=c[j-1]+10;
if(j!=n)
j=j+1;
}
 }
else
{
c[j-1]--;
j=-1;
}
}
printf("\n decremented array");
for(i=0;i<n;i++)>
printf("%d\t",c[i]);
getch();
}

推荐答案

一个简单的增量函数可能如下所示(假设权重最低的值存储在最后):

A simple increment function may look like this (assuming the values with the lowest weight are stored at the end):
void incrementArray(int size, int *arr)
{
    int i;
    for (i = size - 1; i >= 0; i--)
    {
        // Increment value and check for overflow
        // Stop processing if no overflow
        if (++arr[i] < 10)
            break;
        // Overflow: Set item to zero and continue processing
        arr[i] = 0;
    }
}



减量函数类似:


The decrement function would be similar:

if (--arr[i] >= 0)
    break;
arr[i] = 9;


如果我要做这样的事情,我会使用递归并使用我的数组作为指针引用对于数组x [n]我会使用x,通过* x引用它的内容,然后通过x ++移动数组。



'add'的递归函数将检查它的特定参考值x(作为* x)并增加/减少该值,并处理边界条件。边界条件是递归的位置。



你的过程让我想起了一些旧的BCD数据类型。
If I were to do such a thing, I would use recursion and work with my arrays as pointer references for array x[n] I would work with x, reference it's content via *x, and move through the array via x++.

The recursive function for 'add' would check the value in it's particular reference x (as *x) and increment/decrement the value, and handle boundary conditions. The boundary conditions would be where the recursion comes in.

You process reminds me a bit of the old BCD data type.


这篇关于增量和减少数组 - 用我的代码......需要另一个解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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