1. 练习一poj.org的1000题
题目:
- Description
Calculate a+b - Input
Two integer a,b (0<=a,b<=10) - Output
Output a+b - Sample Input
1 2 - Sample Output
3
代码:
1 |
|
2. 练习二
题目:
- Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
- Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.Since 2 has only one digit, return it.
代码:
第一种方法:
1 | //使用递归方法 |
第二种方法:
1 | //使用迭代法 |
3. 练习三poj.org的1004题
题目:
- Description
Larry graduated this year and finally has a job. He’s making a lot of money, but somehow never seems to have enough. Larry has decided that he needs to grab hold of his financial portfolio and solve his financing problems. The first step is to figure out what’s been going on with his money. Larry has his bank account statements and wants to see how much money he has. Help Larry by writing a program to take his closing balance from each of the past twelve months and calculate his average account balance. - Input
The input will be twelve lines. Each line will contain the closing balance of his bank account for a particular month. Each number will be positive and displayed to the penny. No dollar sign will be included. - Output
The output will be a single number, the average (mean) of the closing balances for the twelve months. It will be rounded to the nearest penny, preceded immediately by a dollar sign, and followed by the end-of-line. There will be no other spaces or characters in the output. - Sample Input
100.00
489.12
12454.12
1234.10
823.05
109.20
5.27
1542.25
839.18
83.99
1295.01
1.75
- Sample Output
$1581.42
代码:
1 |
|
4. 练习四poj.org的3980题
题目:
- Description
编写一个C函数mod(int n, int m),实现取模运算% - Input
输入包含多行数据
每行数据是两个整数a, b (1 <= a, b <= 32767)
数据以EOF结束 - Output
于输入的每一行输出a%b - Sample Input
5 3
100 2 - Sample Output
2
0
代码:
1 |
|
注意:
取模与取余的区别:
- 取余运算在计算商值向0方向舍弃小数位
- 取模运算在计算商值向负无穷方向舍弃小数
- 取余,遵循尽可能让商大的原则
- 取模,遵循尽可能让商小的原则
从上面的区别可以总结出,取余(rem)和取模(mod)在被除数、除数同号时,结果是等同的,异号时会有区别,所以要特别注意异号的情况,经过测试,在C/C++, C#, JAVA, PHP这几门主流语言中,’%’运算符都是做取余运算,而在python中的’%’是做取模运算。在C/C++, C#, JAVA, PHP中a对b取模的公式为a-(a/b)*b。