在处理字符串的问题中,经常需要把给定的字符串中的数字字符串转化为整型或者浮点型,下面介绍转化的方法以供参考:
1,不带小数点的转化:
C++ Code
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include<bits/stdc++.h>
using namespace std; int main() { char a[100]; scanf("%s", a); int l = strlen(a); int ans = 0; for(int i = 0; i < l; i++) { ans = ans * 10 + (a[i] - '0'); } printf("%d\n", ans); return 0; } |
2,字符串中带有小数点的情况:
C++ Code
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include<bits/stdc++.h>
using namespace std; int main() { char a[100]; scanf("%s", a); int l = strlen(a); int spot = 0, i; ///spot用来记录小数点的位置 double ans = 0; for( i = 0; i < l; i++) { if(a[i] == '.') spot = i; else ans = ans * 10 + (a[i] - '0'); } if(spot != 0) { i--; ans = ans / pow(10, i - spot); } printf("%lf", ans); return 0; } |
本文介绍了如何将包含整数和浮点数的字符串转换为相应的数值类型。通过两个示例,分别展示了不含小数点的字符串转换为整数,以及含有小数点的字符串转换为浮点数的过程。
2783

被折叠的 条评论
为什么被折叠?



