提示信息

基础编程题集:Java与C语言

情丝 已关注

当然!以下是一些适用于初学者的基础编程题,这些题目可以用Java和C语言来练习。

1. 打印"Hello, World!"

Java:

  1. public class HelloWorld {
  2. public static void main(String[] args) {
  3. System.out.println("Hello, World!");
  4. }
  5. }

C:

  1. #include <stdio.h>
  2. int main() {
  3. printf("Hello, World!\n");
  4. return 0;
  5. }

2. 计算两个数的和

Java:

  1. import java.util.Scanner;
  2. public class Sum {
  3. public static void main(String[] args) {
  4. Scanner scanner = new Scanner(System.in);
  5. System.out.println("Enter two numbers:");
  6. int num1 = scanner.nextInt();
  7. int num2 = scanner.nextInt();
  8. int sum = num1 + num2;
  9. System.out.println("Sum: " + sum);
  10. }
  11. }

C:

  1. #include <stdio.h>
  2. int main() {
  3. int num1, num2, sum;
  4. printf("Enter two numbers:\n");
  5. scanf("%d %d", &num1, &num2);
  6. sum = num1 + num2;
  7. printf("Sum: %d\n", sum);
  8. return 0;
  9. }

3. 判断一个数是奇数还是偶数

Java:

  1. import java.util.Scanner;
  2. public class OddEven {
  3. public static void main(String[] args) {
  4. Scanner scanner = new Scanner(System.in);
  5. System.out.println("Enter a number:");
  6. int num = scanner.nextInt();
  7. if (num % 2 == 0) {
  8. System.out.println(num + " is even.");
  9. } else {
  10. System.out.println(num + " is odd.");
  11. }
  12. }
  13. }

C:

  1. #include <stdio.h>
  2. int main() {
  3. int num;
  4. printf("Enter a number:\n");
  5. scanf("%d", &num);
  6. if (num % 2 == 0) {
  7. printf("%d is even.\n", num);
  8. } else {
  9. printf("%d is odd.\n", num);
  10. }
  11. return 0;
  12. }

4. 打印1到10的数字

Java:

  1. public class PrintNumbers {
  2. public static void main(String[] args) {
  3. for (int i = 1; i <= 10; i++) {
  4. System.out.println(i);
  5. }
  6. }
  7. }

C:

  1. #include <stdio.h>
  2. int main() {
  3. for (int i = 1; i <= 10; i++) {
  4. printf("%d\n", i);
  5. }
  6. return 0;
  7. }

5. 计算数组元素的平均值

Java:

  1. public class Average {
  2. public static void main(String[] args) {
  3. int[] numbers = {10, 20, 30, 40, 50};
  4. int sum = 0;
  5. for (int num : numbers) {
  6. sum += num;
  7. }
  8. double average = (double) sum / numbers.length;
  9. System.out.println("Average: " + average);
  10. }
  11. }

C:

  1. #include <stdio.h>
  2. int main() {
  3. int numbers[] = {10, 20, 30, 40, 50};
  4. int sum = 0;
  5. int length = sizeof(numbers) / sizeof(numbers[0]);
  6. for (int i = 0; i < length; i++) {
  7. sum += numbers[i];
  8. }
  9. double average = (double)sum / length;
  10. printf("Average: %.2f\n", average);
  11. return 0;
  12. }

这些题目可以帮助你熟悉基本的输入输出、条件判断、循环和数组操作的概念。完成之后,你也可以尝试加入一些额外的功能或挑战自己,譬如实现错误处理或更复杂的数据结构。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
情丝 关注 已关注

最近一次登录:2024-11-20 15:28:49   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图