2-1 位数
#include<stdio.h>
#include<math.h>
int main ()
{
int n;
for (n=100; n<=999; n++)
{
if(n == pow(n/100,3) + pow(n/10%10,3) + pow(n%10,3) )
printf("%d\n",n);
}
system("PAUSE");
return EXIT_SUCCESS;
}
2-2 水仙花数
#include<stdio.h>
#include<math.h>
#include <cstdlib>
int main ()
{
int n;
for (n=100; n<=999; n++)
{
if(n == pow(n/100,3) + pow(n/10%10,3) + pow(n%10,3) )
printf("%d\n",n);
}
system("PAUSE");
return EXIT_SUCCESS;
}
2-3 韩信点兵
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int n;
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
for (n = 10; n<=100; n++)
{
if (n%3 == a && n%5 == b && n%7 == c)
{
printf("%d\n",n);
break;
}
}
if (n == 101) printf("No answer\n");
system("PAUSE");
return EXIT_SUCCESS;
}
2-4 倒三角形
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
int i, j, k;
scanf("%d", &n);
for( i = 1; i <= n; i++)
{
for ( k=1; k <= i-1; k++)
printf(" ");
for ( j=i; j <= 2*n-i; j++)
{
printf("#");
}
printf("\n");
}
system("PAUSE");
return 0;
}
总结:printf((j<i || j > m-1-i) ? " " : "#"); 用这句来进行判断输出空格还是#,简单多了
2-6 调和级数
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int n;
double sum = 0;
scanf("%d",&n);
int i;
for(i=1; i<=n; i++)
{
sum += 1.0/i;
}
printf("%.3lf\n", sum);
system("PAUSE");
return 0;
}
2-7 近似计算
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
int i, j;
double sum = 0;
for( i = 1, j = 0; 1.0/i >= 1.0/pow(10,6); i += 2)
{
sum += (1.0/i)*pow(-1,j);
j++;
}
sum += (1.0/i)*pow(-1,j);
printf("%d\n", i);
printf("%.6lf\n", 4*sum);
system("PAUSE");
return 0;
}
总结: 可以用sign = -sign,来进行正负号的转换
2-8 子序列的和
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
int n, m;
scanf("%d %d", &n, &m);
double sum = 0.0;
int i;
for( i = n; i <= m; i++)
{
sum += 1.0/i/i;
}
printf("%.5lf\n", sum);
system("PAUSE");
return 0;
}
总结:仍然是怕溢出,1.0/i/i