?一.題目描述
輸入一個數字,把他轉為字符串
比如:輸入數字:12345
? ????????輸出:12345(這里的12345是字符串12345)
二.思路分析?
比如給定一個數字12345,先把它轉為字符54321(“54321”),(這樣更簡單,如果直接轉為字符12345,還要再求這個數字是幾位數,比較麻煩),然后再將字符串反轉即可。
? ? ? ? ? ? ? ? ?
三.完整代碼
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h> //預編譯
#include<stdlib.h>
#include<string.h>
void Reserve(char* str)
{//把字符串反轉 "54321"->"12345"int low = 0;//左下標int high = strlen(str) - 1;while (low < high){char tmp;tmp = str[high];str[high] = str[low];str[low] = tmp;high--;low++;}
}
void Myitoa(char* str, int n)
{int i = 0;//把數字的個位存放到字符串當中 12345-->"54321" 此時的字符串末尾沒有'\0'for (i = 0; n != 0; i++){str[i] = n % 10 + '0';n /= 10;}str[i] = '\0';//添加字符串結尾標記Reserve(str);
}
int main()
{int n = 12345;char str[20] = "";Myitoa(&str[0], n);printf("轉換為字符串是%s", str);return 0;
}
?四.運行結果
五.補充?
如果使用庫函數,則使用sprintf函數
int main()
{int n;char buf[20] = "";printf("請輸入一個數字 :");scanf("%d", &n);sprintf(buf, "%d", n);printf("%s", buf);return 0;
}
- ?運行結果
創作不易, 如果這份博客👍對你有幫助,可以給博主一個免費的點贊以示鼓勵。