|
发表于 2023-10-25 17:31:04
|
显示全部楼层
本楼为最佳答案
问题1:
#include <stdio.h>
#include <stdlib.h>
void sortNumbers(float *numbers, int size, int order) {
int i, j;
float temp;
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - i - 1; j++) {
if ((order == 0 && numbers[j] > numbers[j + 1]) || (order == 1 && numbers[j] < numbers[j + 1])) {
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
int main() {
int size, order, i;
float *numbers;
printf("请输入要排序的数字个数:");
scanf("%d", &size);
numbers = (float *) malloc(size * sizeof(float));
printf("请输入要排序的数字,以空格分隔:");
for (i = 0; i < size; i++) {
scanf("%f", &numbers[ i]);
}
printf("请选择排序方式(0为从小到大,1为从大到小):");
scanf("%d", &order);
sortNumbers(numbers, size, order);
printf("排序结果:");
for (i = 0; i < size; i++) {
printf("%.2f ", numbers[ i]);
}
free(numbers);
return 0;
}
问题2:
#include <stdio.h>
#include <string.h>
void findCommonChars(char *str1, char *str2) {
int count[128] = {0};
int i;
for (i = 0; i < strlen(str1); i++) {
count[str1[ i]]++;
}
for (i = 0; i < strlen(str2); i++) {
if (count[str2[ i]] > 0) {
count[str2[ i]] = -1;
}
}
printf("相同的字符按ASCII码大小输出:");
for (i = 0; i < 128; i++) {
if (count[ i] == -1) {
printf("%c ", i);
}
}
int commonCount = 0;
for (i = 0; i < 128; i++) {
if (count[ i] == -1) {
commonCount++;
}
}
printf("\n重复字符的个数:%d\n", commonCount);
}
int main() {
char str1[100], str2[100];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
findCommonChars(str1, str2);
return 0;
}
问题3:
#include <stdio.h>
#include <string.h>
void findLongestRepeatedString(char *str1, char *str2) {
int i, j, k;
int len1 = strlen(str1);
int len2 = strlen(str2);
int maxLen = 0, maxIndex = 0;
for (i = 0; i < len1; i++) {
for (j = 0; j < len2; j++) {
if (str1[ i] == str2[j]) {
int len = 0;
for (k = 0; k + i < len1 && k + j < len2; k++) {
if (str1[i + k] != str2[j + k]) {
break;
}
len++;
}
if (len > maxLen) {
maxLen = len;
maxIndex = i;
}
}
}
}
printf("重复且连续最长的字符串输出:%.*s\n", maxLen, str1 + maxIndex);
}
int main() {
char str1[100], str2[100];
printf("请输入第一个字符串:");
scanf("%s", str1);
printf("请输入第二个字符串:");
scanf("%s", str2);
findLongestRepeatedString(str1, str2);
return 0;
}
问题4:
#include <stdio.h>
struct Time {
int year;
int month;
int day;
int hour;
int minute;
};
void printTime(struct Time t) {
printf("%dy%dm%dd%dh%dm\n", t.year, t.month, t.day, t.hour, t.minute);
}
void addTime(struct Time *t, int d, int h, int m) {
t->day += d;
t->hour += h;
t->minute += m;
if (t->minute >= 60) {
t->hour += t->minute / 60;
t->minute %= 60;
}
if (t->hour >= 24) {
t->day += t->hour / 24;
t->hour %= 24;
}
}
int main() {
struct Time t = {23, 7, 29, 17, 27};
int d, h, m;
printTime(t);
while (1) {
printf("请输入要增加的时间(天 小时 分钟),以空格分隔:");
scanf("%d %d %d", &d, &h, &m);
if (d == 0 && h == 0 && m == 0) {
printf("down\n");
break;
}
addTime(&t, d, h, m);
printTime(t);
}
return 0;
}
以上是四个问题的解决方案,请根据需要选择相应的代码进行编译和运行。 |
|