C语言程序设计现代方法第六章答案

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Chapter 6
Answers to Selected Exercises
4. [was #10] (c) is not equivalent to (a) and (b), because i is incremented before the loop body is executed.
10. [was #12] Consider the following while loop:
while (…) {

continue;

}
The equivalent code using goto would have the following appearance:
while (…) {

goto loop_end;

loop_end: ; /* null statement */
}
12. [was #14]
for (d = 2; d * d <= n; d++)
if (n % d == 0)
break;
The if statement that follows the loop will need to be modified as well:
if (d * d <= n)
printf("%d is divisible by %d\n", n, d);
else
printf("%d is prime\n", n);
14. [was #16] The problem is the semicolon at the end of the first line. If we remove it, the statement is now correct:
if (n % 2 == 0)
printf("n is even\n");
Answers to Selected Programming Projects 2. [was #2]
#include <stdio.h>
int main(void)
{
int m, n, remainder;
printf("Enter two integers: ");
scanf("%d%d", &m, &n);
while (n != 0) {
remainder = m % n;
m = n;
n = remainder;
}
printf("Greatest common divisor: %d\n", m);
return 0;
}
4. [was #4]
#include <stdio.h>
int main(void)
{
float commission, value;
printf("Enter value of trade: ");
scanf("%f", &value);
while (value != 0.0f) {
if (value < 2500.00f)
commission = 30.00f + .017f * value;
else if (value < 6250.00f)
commission = 56.00f + .0066f * value; else if (value < 20000.00f)
commission = 76.00f + .0034f * value; else if (value < 50000.00f)
commission = 100.00f + .0022f * value;
else if (value < 500000.00f)
commission = 155.00f + .0011f * value;
else
commission = 255.00f + .0009f * value;
if (commission < 39.00f)
commission = 39.00f;
printf("Commission: $%.2f\n\n", commission);
printf("Enter value of trade: ");
scanf("%f", &value);
}
return 0;
}
6. [was #6]
#include <stdio.h>
int main(void)
{
int i, n;
printf("Enter limit on maximum square: ");
scanf("%d", &n);
for (i = 2; i * i <= n; i += 2)
printf("%d\n", i * i);
return 0;
}
8. [was #8]
#include <stdio.h>
int main(void)
{
int i, n, start_day;
printf("Enter number of days in month: ");
scanf("%d", &n);
printf("Enter starting day of the week (1=Sun, 7=Sat): "); scanf("%d", &start_day);
/* print any leading "blank dates" */
for (i = 1; i < start_day; i++)
printf(" ");
/* now print the calendar */
for (i = 1; i <= n; i++) {
printf("%3d", i);
if ((start_day + i - 1) % 7 == 0)
printf("\n");
}
return 0;
}。

相关文档
最新文档