有n跟棍子,棍子i的长度为ai。想要从中选出3跟棍子组成周长尽可能长的三角形。请输出最大的周长,若无法输出三角形则输出0. //本题目是针对于数组内棍子的长度为小到大的排列

例如:

n = 5 ;

a =  {2,3,4,5,10}

输出: 12 (选择3,4,5时)

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    int i,j,k;          //循环参数
    int temp;
    int longest;        //最长的三角形周长
    int difference,length;          //边差和周长
    char example_array[100];
    scanf("%d",&n);
    for(i = 0 ;i < n ;i++){
        scanf("%d",&example_array[i]);          //对数组的赋值
    }
    longest = example_array[0] + example_array[1] + example_array[2];
    for(i = 0;i < n;i++){
        for(j = i + 1;j < n;j++){
            for(k = j + 1;k < n;k++){                       //三层嵌套循环,重点在每次循环的起始i = 0,j = i + 1;k = j + 1;这样可以减少循环的次数大概节约二分之一
                    length = example_array[k] + example_array[j] + example_array[i];
                    difference = example_array[k] - example_array[j] - example_array[i];
                if(difference < 0 && longest < length){                 //  条件判断,求最大边长
                        temp = length;
                        length = longest;
                        longest = temp;
                }
            }
        }
    }
    printf("%d",longest);·有
}
 

猜你喜欢

转载自blog.csdn.net/xlh006/article/details/81161290