c语言程序设计现代方法第二版习题答案 第四章全部编程题

时间:2021-01-02 11:45:36

已验证通过编译,但不保证在细节上不存在遗漏,仅供参考

4.1

#include <stdio.h>

int main (void)
{
	int num, rev;
	
	printf ("Enter a two-digit number: ");
	scanf ("%2d", &num);
//	这里的%2d是为了只取2位有效数字;
	
	int a, b;
	a = num / 10; //a是十位;
	b = num % 10; //b是个位;
	rev = b * 10 + a;
	
	printf ("The reversal is: %d", rev);	
	
	return 0;
}

4.2

#include <stdio.h>

int main (void)
{
	int num, rev;
	
	printf ("Enter a three-digit number: ");
	scanf ("%3d", &num);
//	这里的%3d是为了只取3位有效数字;
	
	int a, b, c;
	a = num / 100; //a是百位;
	b = num % 100;
	b = b / 10;    //b是十位;
	c = num % 10;  //c是个位; 
	rev = c * 100 + b * 10 + a;
	
	printf ("The reversal is: %d", rev);	
	
	return 0;
}

4.3

#include <stdio.h>

int main (void)
{
	int i1, i2, i3;
	
	printf ("Enter a three-digit number: ");
	scanf ("%1d%1d%1d", &i1, &i2, &i3);
	
	printf ("The reversal is %d%d%d", i3, i2, i1);
	
	return 0;
}

4.4

#include <stdio.h>

int main (void)
{
	int num10, num8; 
	
	printf ("Enter a number between 0 and 32767: ");
	scanf ("%d", &num10);
	
	int a, b, c, e, d;
	a = num10 % 8;
	b = (num10 / 8) % 8;
	c = (num10 / 8 / 8) % 8;
	d = (num10 / 8 / 8 / 8) % 8;
	e = (num10 / 8 / 8 / 8 / 8) % 8;
	
	printf ("In octal, your number is: %d%d%d%d%d", e, d, c, b, a); 
	
	return 0;
}

4.5

#include <stdio.h>

int main (void)
{
	int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5;
	int first_sum, second_sum, total;
	
	printf ("Enter the frist 11 digits of a UPC: ");
	scanf ("%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d",&d, &i1, &i2, &i3, &i4, &i5, &j1, &j2, &j3, &j4, &j5);
	
	first_sum = d + i2 + i4 + j1 + j3 + j5;
	second_sum = i1 + i3 + i5 + j2 + j4;
	total = 3 * first_sum + second_sum;
	
	printf ("Check digit: %d\n", 9 - ((total - 1) % 10));
	
	return 0;
}

4.6 这章题重复的太多了

#include <stdio.h>

int main (void)
{
	int i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12;
	int first_sum, second_sum, total;
	
	printf ("Enter the frist 12 digits of a UPC: ");
	scanf ("%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d", &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8, &i9, &i10, &i11, &i12);
	
	first_sum = i2 + i4 + i6 + i8 + i10 + i12;
	second_sum = i1 + i3 + i5 + i7 + i9 + i11;
	total = 3 * first_sum + second_sum;
	
	printf ("Check digit: %d\n", 9 - ((total - 1) % 10));
	
	return 0;
}