輸入一個10的9次方的正整數(shù),輸出它的位數(shù),。例如輸入123,,的位數(shù)為3。 #include <conio.h> #include<iostream> using namespace std; int main(){ int n,count=1; cin>>n;//輸入n while(n/10>=1){ n = n/10; //cout<<n<<"\n"; count++; } cout<<count;//輸出位數(shù) getch(); return 0; } 水仙花數(shù) #include <conio.h> #include<iostream> using namespace std; int main(){//cout.precision(2); int n,a,b,c; for(n=100;n<=999;n++){ a = n/100;//獲取高位 c = n%10;//獲取低位 b = (n/10)%10;//獲取中位 if(n==a*a*a+b*b*b+c*c*c){//判斷用== cout<<n<<"\n"; } } getch(); return 0; } 韓信點兵 #include <conio.h> #include<iostream> using namespace std; int main(){//cout.precision(2); int n,a,b,c; bool flag = false; cin>>a>>b>>c; for(n=10;n<=100;n++){ if(n%3==a&&n%5==b&&n%7==c){ cout<<n<<"\n"; flag = true; } } if(!flag){ cout<<"No answer"; } getch(); return 0; } 倒三角形 #include <conio.h> #include<iostream> using namespace std; int main(){//cout.precision(2); int i,j,n; cin>>n; for(i=n;i>0;i--){ //空格輸出 for(j=0;j<n-i;j++){ cout<<" "; } //#號輸出 for(j=0;j<2*i-1;j++){ cout<<"#"; } cout<<"\n"; } getch(); return 0; }
#include <conio.h> #include<stdio.h> int main(){ int i,n; double s; scanf("%d",&n); for(i=1;i<=n;i++){//可以舉例判斷是小于還是小于等于 s += 1.0/i; //1.0除以i才可以得到小數(shù),,否則如果是1除以i,則為0 } printf("%.3lf",s); getch(); return 0; } 近似計算 #include <conio.h> #include<stdio.h> int main(){ double pi=0; int i = 1,count = 1; while(1.0/i>=0.000001){ if(count%2 == 1){ pi += 1.0/i; }else{ pi -= 1.0/i; } i += 2; count++; } printf("%.9lf",4*pi); getch(); return 0; }
#include <conio.h> #include<stdio.h> int main(){ double sum = 0; int n,m,t; scanf("%d%d",&n,&m); if(n>m){ t = n; n = m; m = t; } while(n<=m){ sum += 1.0/(n*n);//必須加個括號,不然會從前往后執(zhí)行 n++; } printf("%.5lf",sum); getch(); return 0; }
#include <conio.h> #include<stdio.h> int main(){ int a,b,c,n; double result; scanf("%d%d%d",&a,&b,&c); char s[]="%.0lf\n"; s[2] = c+'0';//動態(tài)設(shè)置精確位數(shù) result = (double)a/b; printf(s,result); getch(); return 0; }
#include <stdio.h> #include <conio.h> int func(int a) { int temp, flag[10] ={1,0,0,0,0,0,0,0,0,0};//把整個數(shù)組初始化為0; for(temp=a%10;a;a/=10,temp=a%10) if(flag[temp]++ == 1) return 0;//如果有相同的位,,則數(shù)組的那個位會被++兩次 return 1; } int main() { int base; for(base=123; base<345; base++) if(func(base*1000000+base*2*1000+base*3)==1) printf("%d %d %d\n", base, base*2, base*3); getch(); return 0; } 我的版本 #include <conio.h> #include<stdio.h> int func(int a){ int temp,flag[10]={1};//定義一個臨時變量和一個十個元素的數(shù)組 //如果初始化時指定的的元素個數(shù)比數(shù)組大小少,,剩下的元素都回被初始化為0。 for(temp=a%10;a;a/=10,temp=a%10)//從末尾開始判斷,,直至全部判斷完成 if(flag[temp]++ == 1) { return 0; }//比較之后再加1,,如果加一之前已經(jīng)為1,說明已存在 return 1; } int main(){ int base; for(base=123;base<329;base++){ if(func(base*1000000+base*2*1000+base*3)==1){ printf("%d %d %d\n", base, base*2, base*3); } } getch(); return 0; } 192 384 576 小結(jié):思路很清晰,,多舉一反三,,看看有哪些方法可以解決之。比較各方法的優(yōu)缺點,。挺好玩的額,。 |
|