整形數字與字元相互轉換
阿新 • • 發佈:2019-01-28
整形轉字元型:
方法一:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char ch[10];
for(int i=0;i<10;i++)
ch[i]='0'+i;
for(int i=0;i<10;i++)
cout<<ch[i];
return 0;
}
方法二:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char ch[10];
for(int i=0;i<10;i++)
ch[i]=i+48;
for(int i=0;i<10;i++)
cout<<ch[i];
return 0;
}
字元型轉換為整形:
方法一:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char ch[10];
for(int i=0;i<10;i++)
ch[i]=i+48;
for(int i=0;i<10;i++)
cout<<ch[i];
cout <<endl;
for(int i=0;i<10;i++)
{
int j=ch[i]-48;
printf("%d",j);
}
return 0;
}
方法二:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char ch[10];
for(int i=0;i<10;i++)
ch[i]=i+'0';
for(int i=0;i<10;i++)
cout<<ch[i];
cout <<endl;
for(int i=0;i<10;i++)
{
int j=ch[i]-'0';
printf("%d",j);
}
return 0;
}
方法三:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char ch[10];
for(int i=0;i<10;i++)
ch[i]=i+'0';
for(int i=0;i<10;i++)
cout<<ch[i];
cout<<endl;
printf("%d",atoi(ch));//將字串轉化為長整形值
return 0;
}