【问题标题】:I need to input 20 numbers and to output only double location我需要输入 20 个数字并只输出双位置
【发布时间】:2017-12-08 14:41:54
【问题描述】:

尝试用数组输入 20 个数字并输出 仅在双重位置的数字,但不知何故打印 也是 0 位置...请帮助。

#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;

for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}

for(i=0;i<n;i++)
{
    if (i%2==0 && i!=1 && i!=0)
    {
        printf("%d\n",num[i]);
    }
}
}

【问题讨论】:

  • “在双位置”和double_locaion 是什么意思?代码中没有使用后者。
  • 双重定位是什么意思?
  • 嗯..我猜双位置是数字的偶数,那是奇数索引....
  • @joemartin94 我不会说清楚,但现在 OP 已经提到它,我想这是有道理的。
  • 使用此信息更新您的问题。请务必包含预期实际输出。

标签: c arrays for-loop


【解决方案1】:

试试这个,从 2 开始,每次增加 2,你不必处理第 0 个元素和奇数个元素。

for (i = 2; i < n; i += 2)
{
    printf("%d\n",num[i]);
}

【讨论】:

  • 请解释一下?
【解决方案2】:

首先,您的代码无法打印数组的0-th 位置。鉴于if 语句的条件,这是不可能

其次,n- 你不需要对该名称使用宏扩展。

/* This program takes 20 integer number from input.
 * Prints the numbers entered in odd positions.(First,Third,..etc).
 */
#include<stdio.h>
#include<stdlib.h>
#define NUM 20
int main(void)
{
    int numArr[NUM];
    for(size_t i = 0; i < NUM; i++) {
        printf("please enter %zu number\n",i+1);
        if( scanf("%d",&numArr[i]) != 1){
            fprintf(stderr, "%s\n","Error in input" );
            exit(1);
        }
    }

    for(size_t i = 0; i < n; i++)
    {
        if( i%2 == 0 )// if you want to omit the first number put the 
                      // the condition (i%2 == 0 && i)
        {
            printf("%d\n",numArr[i]);
        }
    }
    return 0;
}

你的代码跳过了第 0 个元素,你做错了什么?

if (i%2==0 && i!=1 && i!=0)
                      ^^^^

i0 使这个条件为假时 - 你永远无法打印它。

i!=1?

如果i=1 那么i%2 将是1,所以你甚至不会检查第二个条件,整个条件表达式将变为假。所以你可以放心地省略这个逻辑。

有没有更好的办法?

当然,

for(size_t i = 0; i < n; i += 2){
    printf("%d\n",num[i]);
}

说明

如果您认为每次检查 2 的模运算时,结果为 0 的元素仍然是

 0,2,4,6,8,10,...18

看到模式了吗?以0 开始,每次以2 递增,何时停止?是的,在到达20 编码之前,我们得到了

for(size_t i = 0; i < n; i += 2){ 
/*   Initialize with i=0 as first number is 0 (i=0)
 *   Increments by 2 (i+=2) 
 *   Runs when less than 20 (i<n) 
 */
    printf("%d\n",num[i]);
}

如果你想省略第 0 个索引,请正确初始化

for(size_t i = 2; i < n; i += 2){ 

【讨论】:

    【解决方案3】:

    如果你的意思是你想要数组中出现在偶数位置的数字,那么你可以这样做:

    for (i = 2; i < n; i=i + 2) //Initialize i = 0 if 0 is consider as even
    {
        printf("%d\n",arr[i]);
    }
    

    上面的代码 i 初始化为 2,每次迭代的增量为 2,因此它只会访问偶数位置 (2,4,6...) 的元素。

    【讨论】:

    • 好的,零元素呢?
    • 你也想打印零索引元素吗?如果是,那么只需初始化 i=0;
    猜你喜欢
    • 2015-07-13
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2021-11-12
    • 2022-01-15
    相关资源
    最近更新 更多