内容发布更新时间 : 2025/5/23 5:56:44星期一 下面是文章的全部内容请认真阅读。
第3章 分支结构
【练习 3-1】例 3-4 中使用 else-if 语句求解多分段函数,为了检查 else-if 语句的三个分支是否正确,已经设计了三组测试用例,请问还需要增加测试用例吗?为什么?如果要增加,请给出具体的测试用例并运行程序。 解答:
最好再增加两组测试用例,因为尚未对分段函数参数的边界值进行测试。可再给出 x=0和 x=15 时的两种情况。
【练习 3-2】计算符号函数的值: 输入一个整数 x,计算并输出下列分段函数 sign(x)的值。
-1 x<0 y=sign(x)= 0 x=0 1 x>0 解答:
#include
int x, y;
printf(\
scanf(\if(x>0) y=1; else if (x==0) y=0; else y=-1;
printf(\
return 0;
}
【练习 3-3】统计学生平均成绩与及格人数:输入一个正整数 n,再输入 n 个学生的成绩,计算平均成绩,并统计所有及格学生的人数。试编写相应程序。 解答:
# include
int count, i, n;
double grade, total;
printf(\ scanf(\ total = 0; count = 0;
for(i = 1; i <= n; i++){
printf(\ scanf (\
total = total + grade; if(grade >= 60) count++; }
printf(\ printf(\
return 0; }
【练习 3-4】统计字符:输入 10 个字符,统计其中英文字母、空格或回车、数字字符和其他字符的个数。试编写相应程序。 解答:
#include
int i;
int blank, digit, letter, other; char c;
blank = digit = letter = other = 0; for(i=1;i<=15;i++){
c = getchar();
if(c>='a' && c <= 'z' || c>='A' && c <= 'Z')
letter++;
else if(c>='0' && c <= '9')
digit++;
else if(c==' '||c=='\\n')
blank++; else
other++;}
printf(\
k, digit, other);