C语言程序设计题4则

1.有一分数序列2/1,3/2,5/3,8/5,13/8,21/13……编写程序求出这个数列的前20项之和。
2.编写一个程序,对于一个大于或等于3的正整数,判断他是不是一个素数。
3.编写程序,实现对于输入的一行字符,统计其中字母,数字字符,其他字符的个数。
4.编写程序,C=1+1/X^1+1/X^2+1/X^3+……(X>1)直到某一项A<=0.000001时为止,输出最后C的值。

/**测试功能函数:
*1.有一分数序列2/1,3/2,5/3,8/5,13/8,21/13……编写程序求出这个数列的前20项之和。
*2.编写一个程序,对于一个大于或等于3的正整数,判断他是不是一个素数。
*3.编写程序,实现对于输入的一行字符,统计其中字母,数字字符,其他字符的个数。
*4.编写程序,C=1+1/X^1+1/X^2+1/X^3+……(X>1)直到某一项A<=0.000001时为止,
*输出最后C的值。
*作者:pengs
*
*/

#include <iostream>
#include <cmath>

using namespace std;

/*实现第一个功能函数*/
double mark_calc(int n)
{
double a(1.0), b(2.0), sum(0),temp;

while (n > 0)
{
sum += b / a;
temp = b; /*先将b保存后,再更改b的值,然后赋值给a*/
b += a;
a = temp;
--n;
}

return sum;
}

/*判断一个整数是否为素数,如果是,返回true*/
bool isPrime(const int n)
{
int num = n;
int tmp = (int)sqrt(n); /*只需测试到sqrt(n)即可*/

if (num == 1 || num == 2)
return true;

for (int i = 2;i <= tmp; ++i)
if ( num % i == 0)
return false;

return true;
}

/*实现第三个功能函数*/
double intSer(int x)
{
double sum = 0;
double tmp = 1.0 / x;
while (tmp > 0.00001)
{
sum +=tmp;
tmp /=x;
}

return sum;

}

/*统计字符串函数*/
void print_n(const char *ch)
{
int digit = 0;
int letter = 0;
int space_n = 0;
int other = 0;

cout << "原字符串:" << ch << endl;
while (*ch != '\0')
{
if ((*ch >= 'a' && *ch <= 'z') || (*ch >= 'A' && *ch <= 'Z'))
++letter;
else if (*ch == ' ')
++space_n;
else if (*ch >= '0' && *ch <= '9')
++digit;
else
++other;
++ch;
}

cout << "字母(a~z or A~Z)的个数有: " << letter << "个" << endl;
cout << "数字(0~9)的个数有: " << digit << "个" << endl;
cout << "空格的个数有: " << space_n << "个" << endl;
cout << "其他字符的个数有: " << other << "个" << endl;
}

int main(int argc, char *argv[])
{
/*输入一行测试字符*/
char *ch = new char[100];
cout << "统计字符函数测试:请输入一行字符: " << endl;
gets(ch);
print_n(ch);

delete []ch;
ch = NULL;

int num1(20);
cout << "请输入项数:n = " ;
cin >> num1;
cout << "2/1+3/2+5/3+…+前20项之和为:" << mark_calc(num1) << endl;

int num2(10);
cout << "请输入x的值:x = " ;
cin >> num2;
cout << "1/x + 1/x*x + +(1/x^n <= 0.00001)和为:" << intSer(num2) << endl;

int num3;
cout << "请输入一个正整数:n = " ;
cin >> num3;

if (isPrime(num3))
cout << num3 << " 是素数!" << endl;
else
cout << num3 << " 不是素数!" << endl;

return 0;
}

/*建议:
1、应该加入一些输入异常或错误处理;
2、对循环中的出现的终止条件应该使用字符表示,便于修改;
3、时间有限,有些优化略过。(完)*/
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-04-23
1.GetX(n)
{ if(n==1)return 2;
return GetX(n-1) + GetY(n-1);
}
GetY(n)
{ if(n==1)return 1;
return GetX(n-1);
}
CalcOne(n)
{
return GetX(n)/GetY(n);
}
CalcAll(n)
{
int iAll = 0;
for(int i=0; i<n; ++i)
{
iAll += CalcOne(i+1);
}
return iAll;
}
第2个回答  2010-04-23
#include<stdio.h>

void main()
{
int i;
double a = 2,b = 5;
double sum = 0;
for(i = 0;i<20;i++)
{
sum += (a/b);
b = a;
a = a + b;
}
printf("%f",sum);
}
相似回答