【问题标题】:i want to add a constant to an array of numbers but differently in C我想向数字数组添加一个常数,但在 C 中有所不同
【发布时间】:2023-04-04 14:53:01
【问题描述】:

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

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

【问题讨论】:

  • 1 2 3 列表的结果是什么?
  • 您要做的是模算术,运算符% 为您提供整数的余数(或模数)。您只需将增量添加到每个数组元素,然后存储elem%7
  • @bereal 将 3 添加到您的列表中它保持不变
  • 我认为你需要调查modulo operator
  • 遍历数组一次以找到最大元素,我们称之为m。然后再次遍历数组,对每个元素进行加法,并将结果以 m + 1 为模赋值给 back。

标签: c


【解决方案1】:

您所描述的似乎是最大元素 + 1 的模加法,即大于最大元素环绕的总和。

  1. 通过遍历数组找到最大元素,我们称之为max
  2. 再次遍历数组,并为每个元素做加法模max + 1,即概念上arr[i] = (arr[i] + n) % (max + 1)

(如果想要环绕不是为零而是最小元素,那么还要在步骤 1 中找到最小值并在步骤 2 中执行 arr[i] = ((arr[i] - min + n) % (max + 1)) + min。)

【讨论】:

  • (您当然可以通过在循环外预先计算max + 1 和可能的n - min 来优化一点。)
【解决方案2】:

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

#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 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2021-10-01
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多