标签:
1. 输入一个字符串,求它包含多少个单词。单词间以一个或者多个空格分开。
第一个单词前,最后一个单词后也可能有0到多个空格。
比如:" abc xyz" 包含两个单词,"ab c xyz " 包含3个单词。
如下的程序解决了这个问题,请填写划线部分缺失的代码。
注意:只填写划线部分的代码,不要填写任何多余的内容。比如已经存在的小括号,注释或说明文字等。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
using namespace std;
int get_word_num(char* buf)
{
int n = 0;
int tag = 1;
char* p = buf;
for( ;*p!=0&&*p!=13 && *p!=10; p++)
{
if(*p==‘ ‘&&tag==0) tag=1;
if( *p!=‘ ‘ && tag==1 ){
n++; tag=0;
}
}
return n;
}
int main()
{
char buf[1000];
fgets(buf, 1000, stdin);
printf("%d\n", get_word_num(buf));
return 0;
}
2. 1/1 + 1/2 + 1/3 + 1/4 + ... 在数学上称为调和级数。
它是发散的,也就是说,只要加上足够多的项,就可以得到任意大的数字。
但是,它发散的很慢:
前1项和达到 1.0
前4项和才超过 2.0
前83项的和才超过 5.0
那么,请你计算一下,要加多少项,才能使得和达到或超过 15.0 呢?
请填写这个整数。
注意:只需要填写一个整数,不要填写任何多余的内容。比如说明文字。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
using namespace std;
int main()
{
double ans=0;
double i=1.0;
while(ans < 15.0){
ans+=(1.0/i);
i+=1.0;
}
printf("%lf %lf\n", ans, i);
return 0;
}
答案:15.000000 1835422.000000 应为:1835422
3. 如果x的x次幂结果为10(参见【图1.png】),你能计算出x的近似值吗?
显然,这个值是介于2和3之间的一个数字。
请把x的值计算到小数后6位(四舍五入),并填写这个小数值。
注意:只填写一个小数,不要写任何多余的符号或说明。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define eps 1e-7
using namespace std;
int main()
{
double aim = 10.0;
double x;
double L=2.0, R=3.0;
//二分枚举
while(L-R < (-eps))
{
double mid=(L+R)/2;
if( pow(mid,mid) > aim ){
R=mid;
}else{
L=mid;
}
}
printf("%lf\n", pow(L, L)); //最后得到的是9.999999
printf("%lf %lf\n", L, R); //L=R=2.506184
return 0;
}
标签:
原文地址:http://www.cnblogs.com/yspworld/p/5042844.html