一道铺地砖问题,关于向上取整算法。

一道铺地砖问题,关于向上取整算法。

标签(空格分隔): 编程错题 C 双学位高级语言程序设计 编程竞赛


原题如下:
【Problem description】
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city’s anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.What is the least number of flagstones needed to pave the Square? It’s allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It’s not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
【Input】
The input contains three positive integer numbers in the first line: n,  m and a (1 ≤  n, m, a ≤ 105).
【Output】
Write the needed number of flagstones.

大意即为:在一片n×m的广场上铺a×a的地砖,要求地砖全部铺满广场,且地砖不能打碎,但可以延伸出广场,问一共需要多少块地砖。
这道题想起来很好想,无非就是判断n和m能否整除a,如果整除最好说,如果不能整除,就加一相乘。但当时我没想到啊。现在看来,这里有一个向上取整的算法隐藏着。也就是,如果n/m有余数,就加一,没余数,就不加。
具体代码为
i=n/a+(n%a?1:0);
如果n/a有余数,就向上取整,如果没有余数,就不管。

吸收了这个经验,那我们有这样一个向上取整程序:

#include <stdio.h>
int main()
{
    int a;
    float b;
    scanf("%f",&b);
    a = (int)b+((b-(int)b)==0?0:1);
    printf("%d",a);
    return 0; 
}

用一个选择判断运算?:解决了这个问题。
 

posted @ 2017-12-12 08:45  CF过2100就买ARCTERYX  阅读(335)  评论(0编辑  收藏  举报