iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0
自我挑戰組

cpe30天練習系列 第 15

cpe練習day15

  • 分享至 

  • xImage
  •  

今天是練習cpe的Primary Arithmetic題目

程式碼

#include <iostream>
using namespace std;
 
int main() 
{
    int x , y;
    while (cin >> x >> y)
	{	
		int carry=0;
		int tmp=0;
		int count=0;
        if(x == 0 && y == 0)
		{	
			break;
		} 
		while( x > 0 || y > 0)
		{
			tmp = x % 10 + y % 10 + carry;
			if(tmp >= 10)
			{
				carry = tmp / 10;
				count++;
			}
			else
			{
				carry = 0;
			}
			x /= 10;
			y /= 10;
		}
		if(count == 0)
		{
			cout << "No carry operation." << endl; 
		}
		else if(count == 1)
		{
			cout << count << " " << "carry operation." << endl;
		}
		else
		{
			cout << count << " " << "carry operations." << endl;
		}
    }
    return 0;
}

##解題方向

  • if(x == 0 && y == 0) -> 若輸入 0 0,則程式結束,這是題目要求的終止條件
  • tmp = x % 10 + y % 10 + carry; -> 這裡每次取出x和y的個位數,再加上前一輪的進位carry
  • if(tmp >= 10) -> 如果相加結果≥10,就會產生進位
  • x /= 10; y /= 10; -> 把x與y的個位數去掉,繼續往更高位數計算

上一篇
cpe練習day14
系列文
cpe30天練習15
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言