用C语言设计一个文本菜单交互界面的程序,该程序能够实现以下功能: 1. 用户可以输入若干个整数(可能有重复数); 2. 设计文本菜单供用户进行功能选择; 3. 实现数字排序、求出数字的和、求出数字的积等理论课中展示过的功能; 4. 自行设计其他功能(如求取最大、最小值等)。
时间: 2024-10-15 11:21:26 浏览: 27
在C语言中设计一个文本菜单交互界面的程序,你可以按照以下步骤来进行:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义全局变量存储数据
int *numbers;
int num_count = 0;
// 功能函数
void add_numbers(int* arr, int count) {
int sum = 0;
for (int i = 0; i < count; i++) {
sum += arr[i];
}
printf("Sum of the numbers is: %d\n", sum);
}
void multiply_numbers(int* arr, int count) {
int product = 1;
for (int i = 0; i < count; i++) {
product *= arr[i];
}
printf("Product of the numbers is: %d\n", product);
}
void sort_numbers(int* arr, int count) {
// 使用冒泡排序算法
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted numbers are: ");
for (int i = 0; i < count; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// 文本菜单
void menu() {
printf("Menu:\n");
printf("1. Add numbers\n");
printf("2. Multiply numbers\n");
printf("3. Sort numbers\n");
printf("4. Find maximum number\n");
printf("5. Find minimum number\n");
printf("6. Exit\n");
int choice;
scanf("%d", &choice);
switch (choice) {
case 1: add_numbers(numbers, num_count); break;
case 2: multiply_numbers(numbers, num_count); break;
case 3: sort_numbers(numbers, num_count); break;
case 4: printf("Maximum number is: %d\n", *(std::max_element(numbers, numbers + num_count))); break;
case 5: printf("Minimum number is: %d\n", *(std::min_element(numbers, numbers + num_count))); break;
case 6: exit(0); // 退出程序
default: printf("Invalid choice. Please try again.\n");
}
}
int main() {
srand(time(NULL));
while (true) {
printf("Enter integers (type 'q' to quit): ");
char input[50];
fgets(input, sizeof(input), stdin);
if (strcmp(input, "q") == 0) {
free(numbers);
return 0;
}
// 分割字符串为整数并添加到数组中
char* token = strtok(input, " ");
while (token != NULL) {
int num = atoi(token);
numbers = realloc(numbers, (num_count + 1) * sizeof(int));
numbers[num_count++] = num;
token = strtok(NULL, " ");
}
menu();
}
}
```
阅读全文