**C语言编程题解析**
### 程序填空题
**题目描述:**
此题要求学生完成C语言main函数的编写,功能是根据用户输入的字符串和指定字符,删除字符串中该字符及其后的所有字符,但不改变原字符串。输入字符串和字符后,通过while循环检查每个字符,当遇到指定字符时,跳过剩余字符。最后输出处理后的字符串。
```c
main()
{
int i = 0;
char str[N];
char ch;
printf("Input a string:\n");
gets(str); // 使用fgets代替gets,因为gets有安全风险,容易导致缓冲区溢出
printf("\nInput a character:\n");
scanf("%c", &ch);
while (str[i] != '\0') { // 使用索引遍历字符串
if (str[i] == ch) {
while (str[i] == ch) { // 跳过连续的指定字符
i++;
}
} else {
i++; // 非指定字符继续向后移动
}
}
str[i] = '\0'; // 结束字符串
printf("\n***display string***\n");
puts(str);
}
```
**程序修改题**
**题目描述:**
这个题目给出了一个计算数列前n项平方根之和的函数fun(),数列的初始项为0、0、1,后续项为前3项之和。任务是修正错误,使其能正确计算并输出前n项的和。程序中的错误主要集中在计算过程中可能丢失精度或没有正确更新变量。
```c
#include <stdio.h>
#include <math.h>
// 更正后的fun函数
double fun(int n)
{
double sum = 0.0, s0 = 0.0, s1 = 0.0, s2 = 1.0;
int k;
// 去掉多余的条件检查,直接初始化sum为前两项的和
sum = sqrt(s1 + s2);
for (k = 3; k <= n; k++) {
s = s0 + s1 + s2;
sum += sqrt(s); // 无需额外的精度检查,直接累加
s0 = s1;
s1 = s2;
s2 = s;
}
return sum;
}
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Sum of square roots of first %d terms: %.6f\n", n, fun(n));
return 0;
}
```
注意:在修正后的代码中,已经移除了不必要的条件判断`if(n<=2)`,并用`s0`, `s1`, `s2`存储数列的前三个数,这样可以简化计算过程,避免精度损失。同时,在`main`函数中添加了输入n的提示。