如何用C选择数组中的多个元素?

问题描述 投票:2回答:3

有没有办法在C中使用一行代码选择多个元素?例如,假设我有以下代码(假设我已经向用户询问了20个数字,前十个我要求为正数,最后十个我要求为负数):

if (myArray[0 through 9] > 0)
{
  printf("Thank you for providing positive numbers!");
}
else
{
  printf("Sorry, please try again!");
}

if (myArray[10 through 19] < 0)
{
  printf("Thank you for providing negative numbers!");
}
else
{
  printf("Sorry, please try again!");
}

我可以用什么代码代替“通过”?我对这种语言比较陌生,从来没有听说过这样做的方法。我知道有了这个特殊的代码,我可以创建两个数组,一个用于正数,一个用于负数,但我很想知道其他编程项目。

感谢您阅读和回答!

c arrays elements
3个回答
3
投票

没有内置功能,你需要编写一个循环。不要忘记数组索引从0开始。

int all_positive = 1;
int i;
for (i = 0; i < 10; i++) {
    if (myArray[i] <= 0) {
        all_positive = 0;
        break;
    }
}
if (all_positive) {
    printf("Thank you for providing positive numbers!\n");
}

0
投票
int a[20];

// entering values for the array

_Bool first_positive = 1;

for ( size_t i = 0; i < 10 && first_positive; i++ )
{
   first_positive = 0 < a[i];
}

if ( first_positive ) puts( "Hura, first 10 elements are positive" );

_Bool last_negative = 1;

for ( size_t i = 10; i < 20 && last_negative; i++ )
{
   last_negative = a[i] < 0;
}

if ( last_negative ) puts( "Hura, last 10 elements are negative" );

如果你的编译器不支持_Bool,你可以使用类型int而不是类型名称_Bool


0
投票

程序请求行数(1D数组)。然后请求2个整数,整数。然后要求用户选择2行。然后添加2个所选行的总和。

   #include <stdio.h>
   int main ()
   //1D_Array. Load Element and Add Sumline .
   //KHO2016.no5. mingw (TDM-GCC-32) . c-ansi .
   {
   //declare
   int a,b,c,d,e,sum1=0;
   int array[50];
   int i,j,elm1,elm2;

   //valuate
   printf ("Plot a number of elements [1 - 20]: ");
   scanf ("%d",&a);
   printf ("Plot a value : ");
   scanf ("%d",&b);
   printf ("Plot an increment value : ");
   scanf ("%d",&c);

   //calculate
   {for (i<0;i<=a;i++)
   {array[i] =(b+(++c)); // set value for variable [i], inside the array subscript. the vairable [i] must have an INT, and an increment to function !
   sum1 = (sum1 + array[i]);
   printf ("Row [%.2d] : %.2d + %.2d = %d\n",i,b,c,array[i]);}
   printf ("\nSum total = %d\n",sum1);} 
   printf ("\nRow [%.2d] = %d\n",b,array[b]);
   printf ("Row [%.2d] = %d\n",a,array[a]);
   printf ("Select 2 Rows :\n");
   scanf ("%d%d",&elm1,&elm2);
   d=elm1;
   e=elm2;

   printf ("You selected Row [%.2d] = %d\n",d,array[d]);
   printf ("You selected Row [%.2d] = %d\n",e,array[e]);
   printf ("The sum of two selected Rows [%d]+[%d] : %d + %d = %d\n",d,e,array[d],array[e],array[d]+array[e]);
   //terminate
   return 0;
   }
© www.soinside.com 2019 - 2024. All rights reserved.