1、 编写程序,输入年份及月份,输出该月的天数(考虑闰年的情况)。
C语言源码:
#include <stdio.h>
int main() {
int month, year, day;
printf("Year:");
scanf("%d", &year);
printf("Month:");
scanf("%d", &month);
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
day = 29;
} else {
day = 28;
}
break;
default:
day = 30;
}
printf("%d\n", day);
return 0;
}
Python源码:
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
if month in (1, 3, 5, 7, 8, 10, 12):
print(31)
elif month in (4, 6, 9, 11):
print(30)
elif month == 2:
if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0):
print(29)
else:
print(28)
else:
print("输的什么玩意,辣鸡")
2、编写程序求1+3+5+…+99的值并输出。
C语言源码:
#include <stdio.h>
int main() {
int i, s=0;
for (i=1;i<=99;i+=2) {
s += i;
}
printf("%d\n", s);
return 0;
}
Python源码:
s = 0
i = 1
while i <= 99:
s += i
i += 2
print(s)
3、编写程序,用二分法求方程x3-x4+4x2-1=0在[0,1]上的一个实根。
C语言源码:
#include <stdio.h>
#include <math.h>
#define epsilon 1.0e-6
float f(float x) {
return pow(x,3)-pow(x,4)+4*pow(x,2)-1;
}
int main() {
float left, right, middle;
left = 0;
right = 1;
while (fabs(left - right) > epsilon) {
middle = (left + right) / 2;
if (f(middle) == 0) {
break;
}
if ((f(left)>0) && (f(right)<0)) {
if (f(middle) > 0) {
left = middle;
} else {
right = middle;
}
} else {
if (f(middle) < 0) {
left = middle;
} else {
right = middle;
}
}
}
printf("%f\n", middle);
return 0;
}
Python源码:
def f(x):
return x**3-x**4+4*x*x-1
epsilon = 1e-6
left = 0
right = 1
while abs(left - right) > epsilon:
middle = (left + right) / 2
if f(middle) == 0:
print("精确解为:%f" % middle)
break
if f(left) * f(right) < 0:
if f(right) * f(middle) < 0:
left = middle
else:
right = middle
else:
print("算不出来(╯︵╰)")
else:
print("近似解为:%f" % middle)
4、猴子吃桃问题。猴子第一天摘下若干个桃子,当即吃了一半,又多吃了一个。以后每天都吃了前一天剩下的一半多一个。到第10天想再吃时,只剩1个桃子了。求第一天共摘了多少个桃子。
C语言源码:
#include <stdio.h>
int main() {
int peach=0, i, peach2, f;
while (1) {
peach++;
peach2 = peach;
f = 0;
for (i=0;i<9;i++) {
if (peach2 % 2 != 0) {
f = 1;
break;
}
peach2 /= 2;
peach2 -= 1;
}
if (f == 0 && peach2 == 1) {
printf("%d\n", peach);
}
}
return 0;
}
Python源码:
peach = 0
end = False
while not end:
peach += 1
_peach = peach
for i in range(9):
if _peach % 2 != 0:
break
_peach /= 2
_peach -= 1
else:
if _peach == 1:
print(peach)
end = True