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; }