简体   繁体   English

更改 C 中数组值的符号

[英]Changing the sign of array values in C

I need to write a function that takes the elements in an array and changes the sign (ex. 3 --> -3 or -3 --> 3).我需要编写一个 function,它获取数组中的元素并更改符号(例如 3 --> -3 或 -3 --> 3)。 l want use this array (int a[2][3] = { { 55,-44,},{1, -4},{6,11} };) instead of ( int a[] = { 5,6,-4};) What should I do?我想使用这个数组 (int a[2][3] = { { 55,-44,},{1, -4},{6,11} };) 而不是 ( int a[] = { 5, 6,-4};) 我该怎么办?

#include <stdio.h>

void change_sign(int* beta)
{
   for (int i = 0; i < 3; i++) {
      beta[i] = -beta[i];
   }
}

int main(void)
{
   int a[] = { 5, 6, -4};

   for (int i = 0; i < 3; i++) {
      printf("%d ", a[i]);
   }
   printf("\n");
   change_sign(a);
   for (int i = 0; i < 3; i++) {
      printf("%d ", a[i]);
   }
   return 0;
}

For starters it seems you mean this array对于初学者来说,你的意思似乎是这个数组

int a[3][2] = { { 55,-44,},{1, -4},{6,11} };

instead of this而不是这个

int a[2][3] = { { 55,-44,},{1, -4},{6,11} };

In any case if your compiler supports variable length arrays then the function can look like在任何情况下,如果你的编译器支持可变长度 arrays 那么 function 看起来像

void change_sign( size_t m, size_t n, int a[][n] )
{
    for ( size_t i = 0; i < m; i++ )
    {
        for ( size_t j = 0; j < n; j++ )
        {
            a[i][j] = -a[i][j];
        }
    }
}

and call the function like并拨打 function

change_sign( 3, 2, a ); 

Otherwise the function can look like否则 function 看起来像

#define N  2

void change_sign( int a[][N], size_t m )
{
    for ( size_t i = 0; i < m; i++ )
    {
        for ( size_t j = 0; j < N; j++ )
        {
            a[i][j] = -a[i][j];
        }
    }
}

and called like并称呼

change_sign( a, 3 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM