在C語言中,簡化代碼邏輯可以通過以下幾種方法實(shí)現(xiàn):
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(3, 4);
printf("Sum is %d\n", sum);
return 0;
}
#define SQUARE(x) ((x) * (x))
int main() {
int area = SQUARE(5);
printf("Area is %d\n", area);
return 0;
}
if-else
、switch-case
等條件語句,可以使代碼更加清晰。int main() {
int day = 3;
if (day == 1) {
printf("Monday\n");
} else if (day == 2) {
printf("Tuesday\n");
} else if (day == 3) {
printf("Wednesday\n");
} else {
printf("Invalid day\n");
}
return 0;
}
for
、while
、do-while
等循環(huán)語句,可以使代碼更加簡潔。int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++) {
sum += numbers[i];
}
printf("Sum is %d\n", sum);
return 0;
}
struct Point {
int x;
int y;
};
int main() {
struct Point p1 = {3, 4};
struct Point p2 = {5, 6};
int distance = sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
printf("Distance is %f\n", distance);
return 0;
}
通過以上方法,可以使C語言程序的邏輯更加簡潔明了。