【问题标题】:how can I use less variables in my program?如何在我的程序中使用更少的变量?
【发布时间】:2022-06-17 19:22:24
【问题描述】:

我必须制作一个包含数字数组的程序,然后我需要制作一个函数来获取arr[0] 和数组的长度,然后它将打印所有数字而没有重复的数字。

我制作了这个程序,它运行良好,但我觉得我为这个程序使用了太多变量。 (我最近几周开始学习,所以看起来不太好)

#include <stdio.h>

#define N 10

void print_set(int *arr, int n) {
    int i = 1;
    int duplicate_num, check_num, count;
  
    printf(" %d", *arr); //printing the first number (arr[0]).
    
    //starting to check the other number. if they new I'll print them. (start from arr[1]).
    arr++;
    while (i < n) {
        if (*arr != duplicate_num) {
            printf(" %d", *arr);
            check_num = *arr;
            // becouse I found new number, I change it no be equal to the first duplicate_num. (if there are more like him, I change them too).
            while (i < n) {
                if (*arr == check_num) {
                    *arr = duplicate_num;
                }
                arr++;
                i++;
                count++;
            }
            i = i - count;
            arr = arr - count;
            count = 0;
        }
        arr++;
        i++;
    }
}



int main() {
    int arr[N] = {4, 6, 9, 8, 6, 9, 6, 1, 6, 6};
    print_set(&arr[0], N);
    return 0;

}

此程序的输出:4 6 9 8 1

我很高兴看到让这个程序不那么混乱的好方法。

【问题讨论】:

  • 既然您有工作代码并希望得到有关如何改进它的反馈,那么在Code Review 发帖会更合适。

标签: c


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 2015-08-15
  • 2020-05-30
相关资源
最近更新 更多