c - 我想向数字数组添加一个常数,但在 C 中有所不同
问题描述
例如,我有一个包含元素的数组,
0 1 2 3 4 5 6
我想将 3 添加到所有元素并希望输出:
3 4 5 6 0 1 2
添加后的数字不应超过最大元素,而是从最小元素开始。
难以解释。有没有办法在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
推荐阅读
- sharepoint - Sharepoint 无缘无故地显示“正在努力”
- python - Pandas - 如果观察到另一列 (col B) 中的条件,则使用来自另一列 (col A) 的值创建一列 (col C)
- python - 用于多个匹配的 Python 正则表达式
- php - 如何用 PHP 去除问号(字符串)
- python - 如何在 Django 中用 HTML 编写 python 代码?
- react-native - 推送通知中的自定义操作按钮反应原生android
- c# - 如何使用 c# 中的 poco 类和用于 UWP 应用程序的 xaml 显示 json 值
- android - 如何在 Android 中维护不同的调试和生产项目
- java - java - 避免输出用户输入的第一行
- r - R中基于两个不同组的两行条件差