您的位置:首页 > 其它

zoj 1115 Digital Roots

2014-12-25 14:25 267 查看
正确代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
//#include <stdlib.h>
using namespace std;

int main(int argc, char *argv[]) {
string num;
while(cin >> num ){
if(strcmp(num.c_str(),"0")!=0){
int res=0,i=0;
while(num[i]!='\0'){
res+=num[i]-'0';
i++;
}
while(res>=10){
//itoa(res,&num[0],10);
sprintf(&num[0],"%d",res);
i=0; res=0;
while(num[i]!='\0'){
res+=num[i]-'0';
i++;
}
}
cout << res << endl;
}
else break;

}

return 0;
}


分析:
如此简单的一道题我写得却很纠结,因为对int和char之间的转换不熟悉。代码写得也比较乱,还有重复的一个while循环,应该可以简化的。

还可以简化 if(strcmp(num.c_str(),"0")!=0)

成为 while(cin >> num && strcmp(num.c_str(),"0")!=0)

itoa函数只能在vc下使用,它不是一个标准的库函数。不要用它了,使用<stdio.h>下的sprintf,功能相同也更好用。

c++ string类型在使用字符串函数时不同于char*,它需要把“变量名”换成“变量名.c_str()”。例如num换成num.c_str()

c++ string类型在使用springf时要把变量名换成&num[0]。

另外注意,把char型数字传给int型的简单方法 res+=num[i]-'0';
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: