练习题1:
编写一个程序,要求用户输入一段英文句子并在屏幕上逆序输出每个单词(单词间保持原有顺序)。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void reverse_words(char* sentence) {
int start = 0;
int end = 0;
while (sentence[end]) {
if (!isalpha(sentence[end]) && sentence[end] != '\'' && sentence[end] != '-') {
if (end > start) {
for (int i = start; i <= (end - start) / 2; i++) {
char temp = sentence[start + i];
sentence[start + i] = sentence[end - i];
sentence[end - i] = temp;
}
}
start = end + 1;
}
end++;
}
if (end > start) {
for (int i = start; i <= (end - start) / 2; i++) {
char temp = sentence[start + i];
sentence[start + i] = sentence[end - i];
sentence[end - i] = temp;
}
}
}
int main() {
char sentence[100];
printf("Enter an English sentence: ");
fgets(sentence, sizeof(sentence), stdin);
sentence[strcspn(sentence, "\n")] = '\0'; // Remove trailing newline
reverse_words(sentence);
printf("Words reversed: %s\n", sentence);
return 0;
}
练习题2:
编写一个程序,打印出如下所示的乘法表(1到10的乘法表)。
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
...
10 * 10 = 100
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= i; j++) {
printf("%d * %d = %d\t", j, i, i * j);
}
printf("\n");
}
return 0;
}
练习题3:
编写一个程序,接收用户输入的一串数字(以空格分隔),然后按照从小到大的顺序输出这些数字。
#include <stdio.h>
#include <stdlib.h>
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int main() {
int n, num;
int count = 0;
printf("Enter a sequence of integers separated by spaces: ");
while (scanf("%d", &num) == 1) {
count++;
}
rewind(stdin); // Reset input stream after reading with scanf
int* arr = malloc(count * sizeof(int));
printf("Enter the same sequence again:\n");
for (int i = 0; i < count; i++) {
scanf("%d", &arr[i]);
}
qsort(arr, count, sizeof(int), compare);
printf("Sorted sequence: ");
for (int i = 0; i < count; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
return 0;
}
练习题4:
编写一个程序,输出斐波那契数列的前20项,其中第1项和第2项均为1,后续每一项都等于前两项之和。
#include <stdio.h>
int main() {
int a = 1, b = 1;
printf("The first 20 terms of the Fibonacci sequence are:\n");
for (int i = 1; i <= 20; i++) {
printf("%d ", a);
int temp = a;
a = b;
b = temp + b;
}
return 0;
}
练习题5:
编写一个程序,要求用户输入一个整数n(1≤n≤100),然后输出该整数的阶乘。
#include <stdio.h>
long long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int n;
printf("Enter a number between 1 and 100: ");
scanf("%d", &n);
printf("Factorial of %d is %lld\n", n, factorial(n));
return 0;
}