c语言基础知识入门代码
2025-04-16 13:58:36
14
参考资料
C语言基础知识入门代码
1. Hello World程序
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}2. 变量和数据类型
#include <stdio.h>
int main() {
// 基本数据类型
int age = 25;
float height = 1.75f;
double weight = 68.5;
char grade = 'A';
printf("Age: %d\n", age);
printf("Height: %.2f meters\n", height);
printf("Weight: %.1f kg\n", weight);
printf("Grade: %c\n", grade);
return 0;
}3. 运算符
#include <stdio.h>
int main() {
int a = 10, b = 3;
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a %% b = %d\n", a % b);
return 0;
}4. 条件语句
#include <stdio.h>
int main() {
int num = 10;
// if-else语句
if (num > 0) {
printf("Number is positive\n");
} else if (num < 0) {
printf("Number is negative\n");
} else {
printf("Number is zero\n");
}
// switch语句
switch(num) {
case 0:
printf("Zero\n");
break;
case 10:
printf("Ten\n");
break;
default:
printf("Other number\n");
}
return 0;
}5. 循环结构
#include <stdio.h>
int main() {
// for循环
printf("For loop:\n");
for(int i = 0; i < 5; i++) {
printf("%d ", i);
}
printf("\n");
// while循环
printf("While loop:\n");
int j = 0;
while(j < 5) {
printf("%d ", j);
j++;
}
printf("\n");
// do-while循环
printf("Do-while loop:\n");
int k = 0;
do {
printf("%d ", k);
k++;
} while(k < 5);
printf("\n");
return 0;
}6. 数组
#include <stdio.h>
int main() {
// 一维数组
int numbers[5] = {1, 2, 3, 4, 5};
printf("Array elements:\n");
for(int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// 二维数组
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
printf("Matrix:\n");
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}7. 函数
#include <stdio.h>
// 函数声明
int add(int a, int b);
int main() {
int result = add(5, 3);
printf("5 + 3 = %d\n", result);
return 0;
}
// 函数定义
int add(int a, int b) {
return a + b;
}8. 指针基础
#include <stdio.h>
int main() {
int num = 10;
int *ptr = #
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", &num);
printf("Value of ptr: %p\n", ptr);
printf("Value pointed by ptr: %d\n", *ptr);
return 0;
}9. 结构体
#include <stdio.h>
#include <string.h>
// 定义结构体
struct Student {
char name[50];
int age;
float gpa;
};
int main() {
// 创建结构体变量
本文来自《西里网 . 编程语言》 -- 发布时间:2025-03-29
本页链接:https://dev.ciilii.com/show/news-967.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
