zoj 1115 Digital Roots

正确代码:


#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';


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值