C語言程式設計現代方法第二版,第四章課後程式設計習題全部答案

NO IMAGE

已驗證通過編譯,但不保證在細節上不存在遺漏,僅供參考

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;
}