C编程:替换if语句

代码365

您好,这里的新手需要您的帮助。我的C程序很好,并且仅执行了不应使用任何if语句的操作。我认为这样写起来会更容易,因此可以替换if语句。我一直在尝试替换if语句,但是现在卡住了。我可以使用什么代替if语句来产生相同的输出。

该程序应该生成一个在0到9之间的三十个随机整数的序列,然后向前和向后打印该序列。然后打印出一个数字,显示序列中0到9之间的每个数字出现了多少次。

这是输出

Here is a sequence of 30 random numbers between 0 and 9:
 3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 1 8 7 9 2 0 2 3 7 5

Printing them backwards, that's:
  5 7 3 2 0 2 9 7 8 1 6 2 6 0 6 3 9 0 7 2 1 9 2 6 5 3 5 7 6 3

There were 3 0's
There were 2 1's
There were 5 2's
There were 4 3's
There were no 4's
There were 3 5's
There were 5 6's
There were 4 7's
There was only 1 8 
There were 3 9's   

这是我的C程序

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int i, j, array[30]={0}, count=0,check;
    srand(time(NULL));
    for(i=0;i<30;i++)
        array[i]=rand()%10;
    for(i=0;i<30;i++)
        printf("%d ",array[i]);
    printf("\n\n");

    for(i=29;i>=0;i--)
        printf("%d ",array[i]);
    printf("\n\n");

    for(i=0;i<30;i++){
        check=array[i];
        if(array[i]!=-1)
            array[i]=-1;

        if(check == -1)
            continue;

        count =1;

        for(j=0;j<30;j++){
            if((i==j) || (array[j]==-1))
                continue;

            if(check==array[j]){
                count++;
                array[j]=-1;
            }
        }

        printf("There were %d %d's\n",count,check);
    }

    return 0;
}
用户4035

您将从注释中了解算法:

#include <stdio.h>
#include <stdlib.h>
//time.h is needed for time()
#include <time.h>

int main()
{
    int i, array[30] = {0};
    srand(time(NULL));

    //generate and print 30 random numbers
    for(i = 0; i < 30; i++){
        array[i] = rand() % 10;
        printf("%d ", array[i]);
    }

    puts("\n\n");

    //print these numbers backwards
    for(i = 29; i >= 0; i--)
        printf("%d ",array[i]);

    puts("\n\n");

    // print out a count of how many times each number
    // between 0 and 9 appeared in the sequence.
    int count[10] = {0};

    for(i = 0; i < 30; i++)
        count[array[i]]++;

    //output the count for each number
    for(i = 0; i < 10; i++)
        printf("There were %d %d's\n",count[i], i);

    return 0;
}

输出:

9 2 3 9 8 4 3 8 1 3 6 4 3 2 5 3 2 3 0 1 9 0 3 5 1 3 3 8 2 0

0 2 8 3 3 1 5 3 0 9 1 0 3 2 3 5 2 3 4 6 3 1 8 3 4 8 9 3 2 9

There were 3 0's
There were 3 1's
There were 4 2's
There were 9 3's
There were 2 4's
There were 2 5's
There were 1 6's
There were 0 7's
There were 3 8's
There were 3 9's

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章