习题3-4 计算器(calculator)
#include <math.h>
int main()
{
int n1,n2;
char f;
scanf("<strong><span style="color:#ff0000;">%d %c%d</span></strong>",&n1,&f,&n2);
switch(f)
{
case '+': printf("%d", n1 + n2);break;
case '-': printf("%d", n1 - n2);break;
case '*': printf("%d", n1 * n2);
}
return 0;
}
习题3-5 旋转(rotate)
#include <stdio.h>
#include <stdlib.h>
#define N 1000
char array[N][N];
int main()
{
int n, i, j;
scanf("%d", &n);
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
scanf("<span style="color:#ff0000;"><strong> %c</strong></span>",&array[i][j]);
for(j = n - 1; j > -1; j--)
{
for(i = 0; i < n; i++)
printf("%c ",array[i][j]);
printf("\n");
}
return 0;
}
summary:
scanf中%d%c有些小区别。以下是reference:"
Because most conversion specifiers first consume all consecutive whitespace, code such as
std::scanf("%d", &a);
std::scanf("%d", &b);
will read two integers that are entered on different lines (second %d will consume the newline left over by the first) or on the same line, separated by spaces or tabs (second %d will consume the spaces or tabs). The conversion specifiers that do not consume leading whitespace, such as %c, can be made to do so by using a whitespace character in the format string:
std::scanf("%d", &a);
std::scanf(" %c", &c); // ignore the endline after %d, then read a char
%d可以忽略与前一个输入之间的所有空格和TAB,但%c不行,所以在“%c”时把格式写程“ %c”,这样它也就可以忽略与前一个输入之间的所有空格和TAB了
习题3-6 进制转换1(base1)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int base, n, i, count = 0, arr[100];
scanf("%d%d",&base, &n);
while(n != 0)
{
arr[count++] = n % base;
n = n / base;
}
for(i = count - 1; i > -1; i--)
printf("%d", arr[i]);
printf("\n");
return 0;
}
习题3-7 进制转换2(base2)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int base, n, b = 1, sum = 0;
scanf("%d%d",&base, &n);
while(n != 0)
{
sum = sum + b * (n % 10);
b = b * base;
n = n / 10;
}
printf("%d\n",sum);
return 0;
}