如何生成10个随机数并找到第3个最小的 [英] How to generate 10 random numbers and find the 3rd smallest

查看:81
本文介绍了如何生成10个随机数并找到第3个最小的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有这个代码需要完成。它应该生成10个随机的狙击手并找到第三个最小的

任何想法?

Hi,
I have this code that I need to complete. It should generate 10 random snumbers and find the third smallest.
Any ideas?

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Description: 
 *                                                                             *
 * Written by *** for COMP9021                                                 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#define SIZE 10
#define BOUND 10

int main(int argc, char **argv) {
    /* We run the program with one number as command line argument. */
    if (argc != 2) {
        printf("Please provide 1 command line argument.\n");
        return EXIT_FAILURE;
    }
    /* We use it as a seed for the random number generator. */
    srand(strtoul(argv[1], NULL, 10));
    int data[SIZE];
    /* We randomly generate 10 numbers in the range [0, 10) and store them in data. */
    for (int i = 0; i < SIZE; ++i)
        data[i] = rand() % BOUND;
    int third_smallest_number = BOUND;
    /* ... REPLACE THIS COMMENT WITH YOUR CODE ... */
    for (int i = 0; i < SIZE; ++i)
        printf("%4d", data[i]);
    if (third_smallest_number == BOUND)
        printf("\n  does not contain three distinct numbers.\n");
    else
        printf("\n  has %d as third smallest number.\n", third_smallest_number);
    return EXIT_SUCCESS;
}

推荐答案

我们不做你的功课:这是有原因的。它就是为了让你思考你被告知的事情,并试着理解它。它也在那里,以便您的导师可以识别您身体虚弱的区域,并将更多的注意力集中在补救措施上。



亲自尝试,你可能会发现它不是就像你想的那样困难!



但这不是一项艰巨的任务:就个人而言,我会将数据按升序或降序排序,然后才读出来第三小。还有其他方法,但是如果下一个问题是好的,那么第5个最小的是什么?它们是混乱的并且难以维护。
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think!

But this isn''t a difficult task: Personally, I would sort the data into ascending or descending order, and then just read out the third smallest. There are other ways, but they are messy and difficult to maintain if the next question is "OK, so what''s the 5th smallest?"


这篇关于如何生成10个随机数并找到第3个最小的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆