将数组递增到一定数量 [英] Increment array to a certain number

查看:89
本文介绍了将数组递增到一定数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组(代表一个4位数字),我需要对其进行递增,以便每个整数都不会高于3。基本上,它需要打印每一个不包含4或更高数字的4位数字。它。与实际输出相比,这是我期望的输出:

I have an integer array (representing a 4-digit number) that I need to increment so that each integer never goes higher than 3. Basically, it needs to print every 4-digit number that does not have 4 or higher in it. Here's the output I'm expecting compared to the actual output:

Expected: 0000 0001 0002 0003 0010 0011 0012 0013 0020 0021 0022 .... 3333
Received: 0000 1000 2000 3000 3100 3200 3300 3310 3320 3330 3331 3332

我知道我的算法搞砸了,但是我不知道该怎么办:

I know my algorithm's messed up but I don't know what to do to it:

int i, c[4];

memset(c, 0, sizeof(c));
i = 0;
while (1) {
    testprint(c);
    c[i]++;
    if (c[i] == 3)
        i++;
    if (i == 3)
        break;
}

所有 testprint 都可以显示数组中的每个数字。那么,如何更改代码以正确地增加数组?而且我什至需要使用数组吗?

All testprint does is display every digit in the array. So how should I change my code to correctly increment the array? And do I even need to use an array? How would I do this without one?

推荐答案

好吧,我在@chqrlie的帮助下找到了答案:

All right, I found the answer with help from @chqrlie:

int *ito4(int value, int dest[])
{
    int i = 4;
    while (i-- > 0) {
        dest[i] = value % 4;
        value /= 4;
    }
    return dest;
}

int main(void)
{
    int i, arr[4];
    for (i = 0; i < 256; i++)
        print_array(ito4(i, buf), 4);
    return 0;
}

这篇关于将数组递增到一定数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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