跳至主要內容

墨尔本大学C语言期中考

AI悦创原创Python 一对一教学墨尔本大学C语言辅导墨尔本大学C语言一对一辅导墨尔本大学C语言期中考Python 一对一教学墨尔本大学C语言辅导墨尔本大学C语言一对一辅导墨尔本大学C语言期中考大约 5 分钟...约 1417 字

1. Ex7.04: Integer frequencies

1.1 Task

Write a program that reads as many as 1,000 integer values, and counts the frequency of each value in the input.

编写一个程序,读取多达 1000 个整数值,并计算输入中每个值的频率。

1.2 Sample output

There are no tabs in the output.

输出中没有制表符。

Enter as many as 1000 values, ^D to end
1 3 4 6 4 3 6 10 3 5 4 3 1 6 4 3 1
17 values read into array
Value   Freq
   1      3
   3      5
   4      4
   5      1
   6      3
  10      1

Hints

There are two quite different algorithms for this problem. Can you identify both of them? One of them imposes an upper limit on the input values so is less general than the other. Does it have any compensating advantages?

`arrayops.h` available

The arrayops.h library provides the functions read_int_array, int_swap, sort_int_array and print_int_array. You may use it if needed.

1.3 解析

学员代码
#include <stdio.h>

int main() {
    int input_number[1000];
    int input_frequence[1000] = {0};
    int count = 0;
    printf("Enter up to 1000 integer values, Ctrl+D to end:\n");
    while (scanf("%d", &input_number[count]) == 1) {
        count++;
    }
    for (int i = 0; i < count; i++) {
        input_frequence[input_number[i]]++;
        if (input_frequence[input_number[i]] != 0) {

            printf("%d\t%d\n", input_number[i], input_frequence[input_number[i]]);
        }
    }
}
main.c
#include <stdio.h>
#include "arrayops.h"  // 导入arrayops.h库,这个库提供了数组操作的函数。

int main(void) {
    int values[1000];  // 定义一个可以存放最多1000个整数的数组。
    int n, i, current, count;  // 定义变量:n用于存放实际读取的整数数量,i用于循环,current存放当前正在处理的整数,count存放current的频率。

    // 提示用户输入数据
//    printf("Enter as many as 1000 values, ^D to end\n");

    // 使用read_int_array函数读取输入的整数并存放到values数组中。
    // 返回值是实际读取的整数数量。
    n = read_int_array(values, 1000);
    // 输出实际读取的整数数量。
//    printf("%d values read into array\n", n);

    // 对读取的整数进行排序,这样相同的整数将位于数组中连续的位置。
    // 这使得计算每个整数的频率变得简单。
    sort_int_array(values, n);

    // 输出列标题。
    printf("Value   Freq\n");

    // 初始化i为0开始遍历数组。
    i = 0;
    while (i < n) {
        current = values[i];  // 记录当前正在处理的整数。
        count = 0;  // 初始化该整数的频率为0。

        // 如果数组中的当前整数与我们正在处理的整数相同,
        // 则增加频率计数并移动到数组的下一个位置。
        while (i < n && values[i] == current) {
            count++;
            i++;
        }

        // 输出当前整数及其频率。
        printf("%4d%7d\n", current, count);
    }

    return 0;  // 程序结束,返回0。
}
公众号:AI悦创【二维码】

AI悦创·编程一对一

AI悦创·推出辅导班啦,包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发、Web、Linux」,全部都是一对一教学:一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然,还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线,随时响应!微信:Jiabcdefh

C++ 信息奥赛题解,长期更新!长期招收一对一中小学信息奥赛集训,莆田、厦门地区有机会线下上门,其他地区线上。微信:Jiabcdefh

方法一:QQopen in new window

方法二:微信:Jiabcdefh

上次编辑于:
贡献者: AndersonHJB
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度