標籤:style blog color 使用 os io 檔案 for
(1)
#include<iostream>using namespace std;int main(){ int k=0; int j; char b[20]; cout<<"please input an number: "<<endl; cin>>b; for(j=0;j<20&&b[j]!=‘\0‘ ;j++); //字串有一個結束符,判斷它可知是否結束 { k=j; } for(int m=0;m<k;m++) { if(b[m]!=b[k-m-1]) { cout<<"這不是迴文數!"<<endl; return -1;//跳出迴圈 } //不能判斷一個就確定是迴文 } //檢查完畢,是迴文才會到這裡 cout<<"這是迴文數!"<<endl; return 0;}
(2)
#include<iostream>#include<string.h>//這個標頭檔可以使用strlen函數using namespace std;int main(){ int k=0; int m,n; char b[20]; cout<<"please input an number: "<<endl; cin>>b; for (m=0,n=strlen(b) - 1; (m!=n) && (m+1!=n); m++, n--) { if (b[m] != b[n]) { cout<<"這不是迴文數!"<<endl; return -1;//跳出迴圈 }//不能判斷一個就確定是迴文 } //檢查完畢,是迴文才會到這裡 cout<<"這是迴文數!"<<endl; return 0;}
(3)運用指標
#include<iostream>#include<string.h>//這個標頭檔可以使用strlen函數using namespace std;int HuiWen(char*);int main(){ int k=0; int m,n; char b[20]; cout<<"please input an number: "<<endl; cin>>b; if(HuiWen(b)) { cout<<"這是迴文數"; }else { cout<<"這不是迴文數"; } return 0;}int HuiWen(char* s){ if(NULL == s) { return 0; } char *head=s;//指向第一個字元 char *tail=s+strlen(s)-1;//指向最後一個字元 while(true) { if(head >= tail)return 1; if(*head == *tail) { head++; tail--; } else { return 0; } }}