【发布时间】:2015-07-11 21:14:00
【问题描述】:
我尝试编写一个将字符串转换为整数的函数(如 atoi)。我不明白为什么我的函数“convertir”不打印我的变量“res”,而打印了“test 1”“test 2”...“test 4”。我让你看看我的代码,如果你看到不好的地方请告诉我。
#include "stdio.h"
#include "stdlib.h"
int xpown(int x, int n); // x^n
int lent(char str[]); // return length of string
int convertir(char s[]); //convert char to int
int main(){
char s[] ="1234";
convertir(s);
return 0;
}
int xpown(int x, int n){
int res = 1;
while (n != 1){
res= res*x;
n--;
}
return res;
}
int lent(char str[]){
int res =0;
int i=0;
while (str[i] != '\0'){
res=res+1;
i++;
}
return res;
}
int convertir(char s[]){
int res = 0;
int i = lent(s);
int j = 0;
char c = s[j];
while (c != '\0'){
c=s[j];
printf("test %d \n", j);
res = res + (c - 48) * xpown(10,i);
i--;
j++;
}
printf("%d", res);
}
【问题讨论】:
-
您不能在 C++ 中将
#用于 cmets。那些应该是//。 -
好的,谢谢,我编辑
-
为简单起见,您可以使用
c - '0'而不是c - 48来获取一个数字,因为0是一个char,ASCII 码为48。这样,您的代码会变得多一点可读。 -
我不知道谢谢!