21.求S=1 + 1/2 + 1/4 + 1/8 + 1/16 +……
#include <stdio.h>
int main(void)
{
int t_ct;
double time,x;
int limit;
printf("enter the number of terms you want:");
scanf("%d",&limit);
for (time=0,t_ct=1,x=1;t_ct<=limit;t_ct++,x*=2.0)
{
time += 1.0/x;
printf("time = %f when terms = %d.\n",time,t_ct);
}
return 0;
}
运行结果:
enter the number of terms you want:15
time = 1.000000 when terms = 1.
time = 1.500000 when terms = 2.
time = 1.750000 when terms = 3.
time = 1.875000 when terms = 4.
time = 1.937500 when terms = 5.
time = 1.968750 when terms = 6.
time = 1.984375 when terms = 7.
time = 1.992188 when terms = 8.
time = 1.996094 when terms = 9.
time = 1.998047 when terms = 10.
time = 1.999023 when terms = 11.
time = 1.999512 when terms = 12.
time = 1.999756 when terms = 13.
time = 1.999878 when terms = 14.
time = 1.999939 when terms = 15.
22.代码:
#include <stdio.h>
int main(void)
{
int k;
for ( k = 1,printf(“%d:Hi!\n”,k) ; printf(“k = %d\n”,k),
k*k<26 ; k+=2,printf ( “Now k is %d\n”,k) )
printf (“k is %d in the loop\n”,k);
return 0;
}
运行结果:
1:Hi!
k = 1
k is 1 in the loop
Now k is 3
k = 3
k is 3 in the loop
Now k is 5
k is 5 in the loop
Now k is 7
k = 7
23.让程序要求用户输入一个大写字母,使用嵌套循环产生像下面这样的金字塔图案,比如输入E:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
提示:使用一个外部循环来处理行,在每一行中使用三个内部循环,一个处理空格,一个以升序打印字母,一个以降序打印字母。源码如下:
#include<stdio.h>
int main(void)
{
int a;
char i,j,k;
printf("请输入字母:");
scanf(" %c",&i); /*输入的字母用i */
for(k='A' ; k<=i ; k++) /*输入的字母i減掉A的数目就是要做的行数*/
{
for(a=(i-k) ; a>0 ; a--)
printf(" "); /*印出空白字元*/
for(j='A' ; j<=k ; j++)
printf("%c",j); /*递增印出字母*/
for(j=k-1 ; j>='A' ; j--)
printf("%c",j); /*递減印出字母*/
printf("\n");
}
return 0;
}
24. getchar()没有参数,它返回来自输入设备的下一个字符,比如:ch = getchar();相当于scanf(%c,&ch);
putchar()打印出它的参数,比如putchar(ch);相当于printf(“%c”,ch);
这两个函数通常在stdio.h文件中定义,而且通常只是个预处理宏,而不是真正的函数。
25. ctype.h系列字符函数:ctype.h头文件包含了一些函数的原型,这些函数接受一个字符作为参数,如果该字符属于某特定的种类则返回真,否则返回假,比如isalpha()函数判断是否为字母。一些映射函数,比如转换为小写字母tolower()函数,它并不改变原始的参数,它们只返回改变后的值,也就是说,tolower(ch); //对ch没有影响,若要改变ch,可以这样做:ch = tolower(ch);。
26.
27. 求2到num之间的所有数,看它们是否可以整除num,比如求144的约数,由于一次成功的num%div测试可以得到两个约数,拿144除以2,可以得到72,则这两个数均为其约数,这样,我们可以将测试的数缩小到num的平方根即可,而不必到num。如果测试的数是一个完全平方数,就只需打印出一个数。如果测试的数是一个素数,那么程序流程也进不了if语句中,对此我们可设置一个布尔值变量,即标志(flag):
#include <stdio.h> #include <windows.h> // BOOL,TRUE,FALSE包含在windows.h头文件中 int main(void) { unsigned long num; unsigned long div; BOOL isPrime; printf("Please enter an integer for analysis,enter q to quit.\n "); while (scanf("%lu", &num) == 1) { for (div = 2, isPrime= TRUE; (div * div) <= num; div++) { |