在C语言中,可以使用循环结构来重复执行计算。以下是几种常用的循环结构及其示例:
while循环
```c
include
int main() {
int a, b;
char end = ' ';
while (end != 'q') {
scanf("%d %d", &a, &b);
printf("%d\n", a + b);
getchar(); // 消除输入后的回车
end = getchar();
}
return 0;
}
```
do-while循环
```c
include
int main() {
int i = 0;
do {
printf("Hello, world!\n");
i++;
} while (i < 5);
return 0;
}
```
for循环
```c
include
int main() {
for (int i = 0; i < 5; i++) {
printf("Hello, world!\n");
}
return 0;
}
```
使用函数进行重复计算
```c
include
double calculate(double a, double b, char op) {
double result;
switch (op) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
if (b == 0) {
printf("Error: division by zero.\n");
result = 0;
} else {
result = a / b;
}
break;
default:
printf("Error: invalid operator.\n");
result = 0;
}
return result;
}
int main() {
double x, y;
char op;
while (1) {
printf("请输入两个数和一个运算符 (+, -, *, /): ");
scanf("%lf %lf %c", &x, &y, &op);
double result = calculate(x, y, op);
if (result != 0 || op == '/') {
printf("计算结果为: %lf\n", result);
}
}
return 0;
}
```
这些示例展示了如何使用不同的循环结构来重复执行计算任务。你可以根据具体的需求选择合适的循环结构,并在循环体内实现相应的计算逻辑。