日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

C语言 字符串转换成int、long和double型

發(fā)布時(shí)間:2025/5/22 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C语言 字符串转换成int、long和double型 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#include <stdio.h> #include <stdlib.h> #define LENGTH 128int main(void){char str[LENGTH];puts("請(qǐng)輸入字符串:");scanf("%s", str);printf("轉(zhuǎn)換為int型后為 %d。\n", atoi(str));printf("轉(zhuǎn)換為long型后為 %ld。\n", atol(str));printf("轉(zhuǎn)換為double型后為 %lf。\n", atof(str));return 0; }

運(yùn)行結(jié)果:

使用函數(shù)庫(kù):#include <stdlib.h>

函數(shù)原型說(shuō)明返回值
atoiint atoi(const char *nptr)將 nptr 指向的字符串轉(zhuǎn)換為 int 型表示返回轉(zhuǎn)換后的值。結(jié)果值不能用 int 型表示時(shí)的處理未定義
atollong atol(const char *nptr)將 nptr 指向的字符串轉(zhuǎn)換為 long 型表示返回轉(zhuǎn)換后的值。結(jié)果值不能用 long型表示時(shí)的處理未定義
atofdouble atof(const char *nptr)將 nptr 指向的字符串轉(zhuǎn)換為 double 型表示返回轉(zhuǎn)換后的值。結(jié)果值不能用 double 型表示時(shí)的處理未定義

atoi 函數(shù)實(shí)現(xiàn):

int atoi(const char *nptr){int flag = 1;int result = 0;if(nptr == NULL)return 0;while(*nptr == ' ' || *nptr == '\t')nptr++;if(*nptr == '-'){flag = -1;nptr++;}while(*nptr != '\0'){if(*nptr >= 0 && *nptr <= '9'){result = result*10 + (*nptr - '0');} else {break;}nptr++;}return result * flag; }

atol 函數(shù)實(shí)現(xiàn):

int atol(const char *nptr){int flag = 1;long result = 0;if(nptr == NULL)return 0;while(*nptr == ' ' || *nptr == '\t')nptr++;if(*nptr == '-'){flag = -1;nptr++;}while(*nptr != '\0'){if(*nptr >= 0 && *nptr <= '9'){result = result*10 + (*nptr - '0');} else {break;}nptr++;}return result * flag; }

atof 函數(shù)實(shí)現(xiàn):

#include <stdio.h> #define LENGTH 128 typedef enum{false,true} bool;double atof(const char* nptr){double result = 0.0;double d = 10.0;int count = 0;if(nptr == NULL){return 0;}while(*nptr == ' ' || *nptr == '\t'){nptr++;}bool flag = false;while(*nptr == '-'){ flag = true;nptr++;}if(!(*nptr >= '0' && *nptr <= '9')){ return result;} while(*nptr >= '0' && *nptr <= '9'){ result = result * 10 + (*nptr - '0');nptr++;}if(*nptr == '.'){ nptr++;}while(*nptr >= '0' && *nptr <= '9'){ result = result + (*nptr - '0') / d;d *= 10.0;nptr++;}result = result * (flag ? -1.0 : 1.0);if(*nptr == 'e' || *nptr == 'E'){ flag = (*++nptr == '-') ? true : false;if(*nptr == '+' || *nptr == '-'){nptr++;}while(*nptr >= '0' && *nptr <= '9'){count = count*10 + (*nptr - '0');nptr++;}if(flag == true) { while(count > 0){result = result / 10;count--;}}if(flag == false){ while(count > 0){result = result * 10;count--;}}}return result; }int main(void){char str[LENGTH];puts("請(qǐng)輸入字符串:");scanf("%s", str);printf("轉(zhuǎn)換為double型后為 %f。\n", atof(str));return 0; }

總結(jié)

以上是生活随笔為你收集整理的C语言 字符串转换成int、long和double型的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。