问题描述:输入两数,统计两数相加的进位个数
My Code:
//精简代码 #include<iostream> using namespace std; int main() { int a, b, c, cnt; while(cin >> a >> b) { c = cnt = 0; while(a || b) { c = ((a%10 + b%10 + c) > 9) ? 1 : 0; cnt += c; a /= 10; b /= 10; } cout << cnt << endl; } return 0; }
//First #include<iostream> using namespace std; const int size = 100; void main() { int a, b; cout << "Enter two numbers(0 0 to end):" << endl; while(cin >> a >>b && a != 0 && b != 0) //0 0 结束输入标志 { int a1[size] = {0}, a2[size] = {0}; //模拟数组 int i = 0; while(a) //整数a转换存储到数组中 { a1[i] = a%10; a /= 10; ++i; } i = 0; while(b) //整数b转换存储到数组中 { a2[i] = b%10; b /= 10; ++i; } int len1, len2, cnt = 0; len1 = sizeof(a1)/sizeof(*a1); //a的位数 len2 = sizeof(a2)/sizeof(*a2); //b的位数 for(i = 0; i < (len1>len2?len1:len2); ++i) if(a1[i] + a2[i] > 9) { ++cnt; ++a1[i+1]; } cout << cnt << endl; } }
Identifying Code:
#include<iostream> void main() { int a, b; cout << "Enter two numbers(0 0 to end):" << endl; while(cin >> a << b && a != 0 && b != 0) { int carry = 0, cnt = 0;//进位和计数 for(int i = 9; i >= 0; --i) //int型表示所有9位整数 { carry = (a%10 + b%10 + carry) > 9 ? 1 : 0; //根据当前有进位情况为进位carry赋值 ans += carry; //更新计数器 a /= 10; b /= 10; } cout << ans << endl; } }
比较:
相较于Identifying而言,my code以下几点有待改进:
(1)、深刻理解问题实质;;
(2)、变量少些,精简代码;
属于小技巧,多多练习,掌握它……
关于int、double、long、char的所能表示范围在我的CSDN博客中有专门测试
点击链接:桑海的CSDN博客