首页 > 解决方案 > 我想向数字数组添加一个常数,但在 C 中有所不同

问题描述

例如,我有一个包含元素的数组,
0 1 2 3 4 5 6
我想将 3 添加到所有元素并希望输出:
3 4 5 6 0 1 2添加后的数字不应超过最大元素,而是从最小元素开始。

难以解释。有没有办法在c中做到这一点?(不是 C++)

标签: c

解决方案


如果我理解正确,您需要以下内容。

#include <stdio.h>

size_t max_element( const int a[], size_t n )
{
    size_t max = 0;

    for ( size_t i = 1; i < n; i++ )
    {
        if ( a[max] < a[i] ) max = i;
    }

    return max;
}

int main(void)
{
    int a[] = { 0, 1, 2, 3, 4, 5, 6 };
    const size_t N = sizeof( a ) / sizeof( *a );

    int value = 0;

    printf( "Enter a value to add to elements of the array: " );
    scanf( "%d", &value );

    size_t max = max_element( a, N );

    int upper_value = a[max] + 1;

    for ( size_t i = 0; i < N; i++ )
    {
        a[i] = ( a[i] + value ) % upper_value;
    }

    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );
}

程序输出可能看起来像

Enter a value to add to elements of the array: 3
3 4 5 6 0 1 2 

推荐阅读