《算法竞赛入门经典》第一章 程序设计入门 习题

习题1-1 平均数(average)
输入三个数,输出他们的平均值,保留3位小数。

#include <stdio.h>
int main() {
    double a, b, c;
    scanf("%lf%lf%lf", &a, &b, &c);
    printf("%.3lf", (a+b+c)/3);
    return 0;
}

习题1-2 温度(temperature)
输入华氏温度f,输出对应的摄氏温度c,保留3位小数。提示:c=5(f-32)/9。

#include <stdio.h>
int main() {
    double f;
    scanf("%lf", &f);
    printf("%.3lf", 5 * (f - 32) / 9);
    return 0;
}

习题1-3 连续和(sum)
输入正整数n,输出1+2+3+……+n的值。提示:目标是解决问题,而不是练习编程。

#include <stdio.h>
int main() {
    int n;
    scanf("%d", &n);
    printf("%d", (n + 1) * n / 2);
    return 0;
}

习题1-4 正弦和余弦(sincos)
输入正整数n(n<360),输出n度的正弦、余弦函数值。提示,使用数学函数。

#include <stdio.h>
#include <math.h>
#define pi acos(-1.0)
int main() {
    int degree;
    scanf("%d", &degree);
    printf("%.3lf\n", sin(1.0 * pi * degree / 180.0));
    printf("%.3lf\n", cos(1.0 * pi * degree / 180.0));
    return 0;
}

习题1-5 距离(distance)
输入4个浮点数x1,y1,x2,y2,输出平面坐标系中点(x1,y1)到(x2,y2)的距离。

#include <stdio.h>
#include <math.h>
int main() {
    double x1, y1, x2, y2;
    scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
    double dis = sqrt(pow(x1-x2, 2.) + pow(y1-y2, 2.));
    printf("%.3lf", dis);
    return 0;
}

习题1-6 偶数(odd)
输入一个整数,判断它是否为偶数。如果是,则输出"yes",否则输出"no"。提示:可以用多种方法判断。

#include <stdio.h>
#include <math.h>
int main() {
    double x1, y1, x2, y2;
    scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
    double dis = sqrt(pow(x1-x2, 2.) + pow(y1-y2, 2.));
    printf("%.3lf", dis);
    return 0;
}

习题1-7 打折(discount)
一件衣服95元,若消费满300元,可打八五折。输入购买衣服件数,输出需要支付的金额(单位:元),保留两位小数。

#include <stdio.h>
int main() {
    int n;
    scanf("%d", &n);
    printf("%.2lf", 95 * n >= 300 ? 95.0 * n * 0.85 : 95 * n);
    return 0;
}

习题1-8 绝对值(abs)
输入一个浮点数,输出他的绝对值,保留两位小数。

#include <stdio.h>
#include <math.h>
int main() {
    double f;
    scanf("%lf", &f);
    printf("%.2lf", fabs(f));
    return 0;
}

习题1-9 三角形(triangle)
输入三角形三边长度值(均为正整数),判断它是否能为三角形的三个边长。如果可以,则输出"yes",如果不能,则输出"no"。如果根本无法构成三角形,则输出"not a trangle"。

#include <stdio.h>
#include <algorithm>
int main() {
    int a[3];
    for (int i = 0; i < 3; i ++)
        scanf("%d", a + i);
    std::sort(a , a + 3);
    if (a[0] + a[1] <= a[2])
        puts("not a trangle");
    else if (a[0] * a[0] + a[1] * a[1] != a[2] * a[2])
        puts("no");
    else
        puts("yes");
    return 0;
}

习题1-10 年份(year)
输入年份,判断是否为闰年。如果是,则输出"yes",否则输出"no"。提示,简单的判断除以4的余数是不够的。

#include <stdio.h>
#include <algorithm>
int main() {
    int year;
    scanf("%d", &year);
    puts(year%400==0 || year%100!=0 && year%4==0 ? "yes" : "no");
    return 0;
}

 

posted @ 2016-06-23 19:56  月光诗人  阅读(458)  评论(0编辑  收藏  举报