基础编程题集:Java与C语言
当然!以下是一些适用于初学者的基础编程题,这些题目可以用Java和C语言来练习。
1. 打印"Hello, World!"
Java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
C:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
2. 计算两个数的和
Java:
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter two numbers:");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}
C:
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter two numbers:\n");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("Sum: %d\n", sum);
return 0;
}
3. 判断一个数是奇数还是偶数
Java:
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}
C:
#include <stdio.h>
int main() {
int num;
printf("Enter a number:\n");
scanf("%d", &num);
if (num % 2 == 0) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}
return 0;
}
4. 打印1到10的数字
Java:
public class PrintNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
C:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
5. 计算数组元素的平均值
Java:
public class Average {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println("Average: " + average);
}
}
C:
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int sum = 0;
int length = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < length; i++) {
sum += numbers[i];
}
double average = (double)sum / length;
printf("Average: %.2f\n", average);
return 0;
}
这些题目可以帮助你熟悉基本的输入输出、条件判断、循环和数组操作的概念。完成之后,你也可以尝试加入一些额外的功能或挑战自己,譬如实现错误处理或更复杂的数据结构。