이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

The Knights Of The Round Table

아서 왕이 천장에 삼각형 창이 있는 방에 원탁을 놓을 계획을 세우고 있다. 그는 햇빛이 원탁 위에 비추게 하고 싶다. 특히 정오에 태양이 바로 머리 위에 있을 때는 원탁 전체에 햇빛이 비추도록 하려고 한다.

그래서 그 원탁은 방 안의 특정한 삼각형 영역 안에 자리잡아야 한다. 물론 아서 왕은 주어진 조건 내에서 최대한 큰 원탁을 만들고 싶어한다.

멀린이 점심을 먹으러 나간 사이에 해가 비추는 영역에 들어갈 수 있는 가장 큰 원탁의 반지름을 계산하는 프로그램을 만들어야 한다.

이미지출처: 위키피디아

Input

테스트 케이스의 개수에는 제한이 없으며, 각 테스트 케이스마다 삼각형의 세 변의 길이를 나타내는 실수 세 개(a,b,c)가 입력된다. 어떤 변의 길이도 1,000,000을 넘지 않으며, max(a,b,c) ≤ (a+b+c)/2 라고 가정해도 된다.

파일 끝에 다다를 때까지 계속 입력을 받는다.

output

각 테스트 케이스마다 다음과 같은 결과를 출력한다.

The radius of the round table is: r

여기에서 r은 정오에 해가 비추는 영역에 들어갈 수 있는 원탁의 최대 반지름이며, 소수점 셋째 자리까지 반올림한 값을 출력한다.

Sample Input

12.0 12.0 8.0

Sample Output

The radius of the round table is: 2.828

2014/03/27 08:57

pahkey

r 을 구하는 것은 어렵지 않습니다. 그러나 "제가 이해못한 것은 파일 끝에 다다를때가지 계속 입력을 받는다" 라는 조건입니다. 이게 무슨 말씀이신지요? 출력을 write할 파일을 생성한후 사이즈를 제한하여 사이즈에 다다를때가지 입력을 받아 채우라는 것인지? 변의 길이에 맞는 난수를 생성하여 r을 계속 찾아내되 한변이 1,000,000 에 근접할 때까지 하라는 것인지? 좀 더 명확하게 해주셨으면 합니다. 답들을 보면 r만 구하였는데 이게 원하는 정답은 아닐 거 같아서요. - 예강효빠, 2017/05/28 00:32
@예강효빠님, "파일 끝에 다다를때까지 계속 입력을 받는다" 라는 말은 Input에 대한 내용입니다. 위 예는 Input 문자열이 한줄이지만 여러줄일 수 있겠죠? 1줄일수도, 2줄일수도, N줄일수도 있습니다. 파일 끝에 다다를때까지라는 말은 이렇게 여러줄일 경우 파일 끝까지 모든 줄을 읽으라는 말입니다. 이해가 되셨기를 바랍니다. - pahkey, 2017/05/28 10:42
@길가의풀님, 아! 고맙습니다. 정확하게 표현하자면 "입력은 파일 끝에 다다를 때 까지 계속 받는다" 라는 의미이군요. 어떻게 읽으면 입력을 계속 하되 어디엔가 다다를때 까지 입력한다 라고 읽혀서요. clear! 그렇다면 입력조건을 txt 로 넣고 readlines 하는게 좋겠군요. 고맙습니다. - 예강효빠, 2017/05/28 11:43
매일 햇빛의 입사각이 달라지고 햇빛이 비치는 영역도 이동할테니 이를 고려한 내용 혹은 가정도 문제에 추가 됐으면 합니다. 예: "아더왕이 말하길, 매년 4월21일 (로마 판테온 신전의 lighting effect 관찰 가능일)에만 성스러운 원탁에 햇빛이 가득하면 된다." - Changmin Mun, 2019/02/09 21:53

121개의 풀이가 있습니다.

구하는 값은 내심의 반지름 r인데요. 내심에서 각 변으로 발을 내리면 수직하므로, 즉 해당 변을 밑변으로 하고 다른 한 점을 내심으로 하는 삼각형의 높이가 되죠.

삼각형의 넓이는 따라서 1/2 * (a+b+c) * r이 됩니다. 동시에 헤론의 공식을 사용해서 a,b,c만으로 넓이를 구할 수 있죠.

양변을 같은 값으로 놓고 r을 유도하면 답이 됩니다.

#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;

int main(void){
    double a, b, c;
    cin >> a >> b >> c;

    // heron's formula
    double s = (a+b+c)/2;
    double S = sqrt(s * (s-a) * (s-b) * (s-c));

    // S = 1/2 *(a+b+c) * r 
    // r = 2S / (a+b+c)

    double r = 2 * S / (a+b+c);

    cout << "The radius of the round table is:" << ios::fixed <<  setprecision(3) << r << "\n";
    return 0;
}

2014/03/27 16:02

Kim Jaeju

#파이썬 3.5.1
#꼭 띄어쓰기 없는 3개의 변수를 띄어쓰기 구분하여 쓰셔야 합니다
#예: 12.0 12.0 8.0 ;O / 1 2 . 0 1 2 . 0 8 . 0 ;X / 12.0*12.0*8.0 ;X / ads wet gry ;X
#안 그러면 종료됩니다.

from math import *

while True:
    inp = input()
    if len(inp.split()) != 3:
        break
    a,b,c = map(float,inp.split())
    s = (a+b+c)/2
    heron = sqrt(s*(s-a)*(s-b)*(s-c))
    r = heron/s # 1/s = 2/(a+b+c)
    print('The radius of the round table is: {0:.3f}'.format(r))

2016/04/30 22:00

차우정

'''
s = (a+b+c)/2,
S = sqrt( s(s-a)(s-b)(s-c) ) = 1/2 * r * (a+b+c) = s * r
=> r = S / s
'''

with open("input.txt", "r") as f:
    a, b, c = map(float, f.readline().split())
    s = (a + b + c) / 2
    S = (s * (s - a) * (s - b) * (s - c)) ** 0.5
    r = S / s
    print("The radius of the round table is: ", round(r, 3))

2018/08/01 07:03

Noname

import math

num = list(map(float,input().split(' ')))
p = sum(num)/2
S = math.sqrt(p*(p-num[0])*(p-num[1])*(p-num[2]))
print(round(S/p,3))

#### 2017.01.19 D-399 ####

2017/01/19 23:16

GunBang

윗분의 도움으로 날로먹었습니다. [..] 해론의 공식말고 다른 해법이 있을까요?

Triangle =
  Struct.new(:a, :b, :c) do
    def area
      s = perimeter / 2
      (s * (s - a) * (s - b) * (s - c))**0.5
    end

    def perimeter
      a + b + c
    end

    def r
      2 * area / perimeter
    end
  end
puts "The radius of the round table is: %.3f" % Triangle.new(12.0, 12.0, 8.0).r

2014/12/12 22:26

Shim Won

Perl
딱히 다른 방법은 없는 것 같네요.

use strict;
while(<>){
    chomp $_;
    my @n=split(" ",$_);
    printf("The radius of the round table is: %.3f\n",sqrt(($n[0]**2+$n[1]**2+$n[2]**2)**2-2*($n[0]**4+$n[1]**4+$n[2]**4))/2/($n[0]+$n[1]+$n[2]));
}

2015/01/11 15:26

*IDLE*

C#으로 작성했습니다. 저는 위에 김재주 님의 설명을 보고도 이해가 안되어서 제가 또 찾아서 (같은 방법으로) 문제를 풀었습니다. 삼각형 안의 원헤론의 공식 위키 링크 겁니다.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CodingDojang
{

    class CodingDojang
    {
        static void Main(string[] args)
        {
            TheKnightsOfTheRoundTable.Answer();
        }
    }

    public class TheKnightsOfTheRoundTable
    {

        public static void Answer()
        {
            var dummy = 0;
            string input = Console.ReadLine().ToString();

            while(dummy == 0)
            {

                List<string> triangle = input.Split(' ').ToList();

                double a = double.Parse(triangle[0]);
                double b = double.Parse(triangle[1]);
                double c = double.Parse(triangle[2]);

                double temp = (a + b + c) / 2;

                double area = Math.Sqrt(temp * (temp - a) * (temp - b) * (temp - c));

                double radius = area / temp;

                Console.WriteLine("The radius of the round table is: " 
                    + Math.Round(radius, 3));

                input = Console.ReadLine().ToString();

                if (input.Length == 0)
                    break;

            }

        }

        public decimal FindMaxRadius(List<decimal> inputs)
        {
            var a = inputs[0];
            var b = inputs[1];
            var c = inputs[2];
            var temp = (a + b + c) / 2;
            var area = (decimal)Math.Sqrt((double)(temp * (temp - a) * (temp - b) * (temp - c)));
            return Math.Round(area / temp, 3);
        }

    }

}

2015/02/13 19:45

Straß Böhm Jäger

public class RoundTable {
    public static void main(String[] args) {
        double a, b, c;

        Scanner sc = new Scanner(System.in);
        while(true) {
            a = sc.nextDouble();
            b = sc.nextDouble();
            c = sc.nextDouble();
            sc.nextLine();

            if(a < 0.0000000d || b < 0.0000000d || c < 0.0000000d ||
                    a >= 1000000d || b >= 1000000d || c >= 1000000d)
                return;

            double s = (a + b + c) / 2;
            double r = Math.sqrt(s * (s - a) * (s - b) * (s - c)) / s;

            System.out.println("The radius of the round table is: " + (Math.round(r * 1000) / 1000d));
        }
    }
}

2015/07/22 09:17

고영감

import math

k = [ float(i) for i in raw_input().split() ]
if max(k) <= 1000000 or max(k) <= (k[0]+k[1]+k[2])/2:
    s = (k[0]+k[1]+k[2])/2
    S = math.sqrt((s*(s - k[0]))*(s - k[1])*(s - k[2]))
    r = S * 2 / (k[0]+k[1]+k[2])
    print "The radius of the round table is : ",round(r,3)

2016/01/03 16:01

Seo

a = input("Length of the triangle's first side:")
b = input("Length of the triangle's second side:")
c = input("Length of the triangle's third side:")

if max(a, b, c) >= min(a,b,c) + (a+b+c-max(a,b,c)-min(a,b,c)):
    print "That's not a triangle"
else:
    r = (((-a+b+c)*(a-b+c)*(a+b-c)/(a+b+c))**0.5)/2
    print "The radius of the round table is:%d" %(r)

헤론의 공식이랑 내접원의 반지름을 통한 삼각형 공식으로 반지름을 구했습니다.

2016/01/11 11:07

취미로재미로

def r(a,b,c):
    return ((b+c-a)*(c+a-b)*(a+b-c)/4/(a+b+c))**0.5

2016/01/23 19:16

상파

#coding: CP949
a=float(input('삼각형의 한 변의 길이를 입력해라(1,000,000):'))
b=float(input('삼각형의 한 변의 길이를 입력해라(1,000,000):'))
c=float(input('삼각형의 한 변의 길이를 입력해라(1,000,000):'))

sin_theta = (1-((a**2+b**2-c**2)/(2*a*b))**2)**0.5
r= ((a*b)*sin_theta)/(a+b+c)
print('%0.3f' % r)

파이썬 3.4

굳이 헤론의 공식을 몰라도 삼각형 내접원 반지름, 코사인 법칙을 이용해도 될 것 같습니다. 물론 궁극적으론 거의 같은 방법이지만,,

2016/02/26 18:24

lovegalois2

헤론의 공식으로 구한 삼각형의 넓이 == 내접원의 반지름을 이용한 삼각형의 넓이로 구했습니다.

def do():
    a, b, c = [float(x) for x in input().split()[:3]]
    r =((2*a*b + a*a + b*b - c*c)*(2*a*b - a*a - b*b + c*c))**0.5 / (2 * (a + b + c))
    print("The radius of the round table is:", round(r, 3))
do()

2016/05/10 14:16

룰루랄라

헤론의 공식으로 삼각형의 넓이를 구하고 또 다른 삼각형의 넓이 구하는 공식 이용하여 삼각형 내접원의 반지름을 구한다.

Python 3.4.4

import cmath

a, b, c = map(float, input().split())

s = (a + b + c) / 2
heron = cmath.sqrt(s * (s - a) * (s - b) * (s - c))
r = heron * 2 / (a + b + c)

print("The radius of the round table:", round(r.real, 3))

2016/05/12 14:02

SanghoSeo

import math
num=input().split(" ")
a=float(num[0])
b=float(num[1])
c=float(num[2])
area1=0.5*a*b*(math.sqrt(1-((a**2+b**2-c**2)/(2*a*b))**2)) # 헤론의 공식
radi=float((area1*2)/(a+b+c)) #내접 반지름 구하기

print("radius= ", round(radi,3))

2016/05/28 01:54

Dr.Choi

Ruby

r = ->a,b,c,s=(a+b+c)/2 { ((s-a)*(s-b)*(s-c)/s)**0.5 }
r_t = proc {puts "The radius of the round table is: %.3f" % r[*gets.split.map(&:to_i)] }

Test

expect(r[12,12,8]).to eq 2.8284271247461903
#=> for stdin/out test
$stdin = StringIO.new("12 12 8\n")
expect { r_t[] }.to output("The radius of the round table is: 2.828\n").to_stdout

Output

#=> r_t[]
12 12 8
"The radius of the round table is: 2.828"

2016/05/31 19:53

rk

from math import *
while __name__ == '__main__':
    s = a, b, c = [*map(float, input('>>>').split())]
    s = sum(s)/2
#삼각함수
    print((a*b*sin(acos((a**2+b**2-c**2)/(2*a*b))))/(a+b+c))
#헤론의 공식
    print(eval('*'.join('(s - '+x+')' for x in [*'0abc']))**0.5/s)

역삼각함수랑 헤론의 공식 두 가지 방법으로 풀었습니다. 파이썬 3.5.2 64 헤론의 공식이 더 정밀하게 나옵니다.

참고: acos의 치역은 0에서 파이까지이므로, sin(acos(x))의 치역은 0~1입니다.

>>>12 12 8

2.82842712474619

2.8284271247461903

2016/11/06 16:59

Flair Sizz

import math
def r(a, b, c):
    if min(a,b,c) < 1000000 and not max(a,b,c) <= (a+b+c)/2:
        raise Exception('min(a,b,c) < 1000000 and max(a,b,c) <= (a+b+c)/2')
    s = (a + b + c) / 2
    S = math.sqrt(s * (s - a) * (s - b) * (s - c))
    rr = 2 * S / (a + b + c)
    print('The radius of the round table is:{:0.3f}'.format(rr))
r(float(input("1:")), float(input("2:")), float(input("3:")))

Python 3.5.2에서 작성하였습니다.

2016/11/28 14:19

Yeo HyungGoo

def length(a,b,c):
    s = (a+b+c) / 2
    N = (s*(s-a)*(s-b)*(s-c))**(1/2) #헤론의공식
    r = 2*N / (a+b+c)

    print(r)
    return ()

length(12,12,8)

2016/12/27 23:43

Kim Da Seul

a,b,c = map(int, input().split(' '))
MM=(((a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c))**0.5)*(0.25)
R=(MM*2)/(a+b+c)
print(R)

2017/01/10 01:20

Dr.Choi

초딩적인 생각으로...

먼저 높이를 구하고 밑변하고 곱해 넓이를 구하고...

내심을통한 반지름을 구하~

#include <stdio.h>
#include <math.h>

void main() {
    double a = 12.0, b = 12.0, c = 8.0;
    double x = (pow((double)a, 2) - pow((double)b, 2) + pow((double)c, 2))/(2*c);
    double y = sqrt(pow((double)a, 2) - pow((double)x, 2));
    double s= (y * c) / 2;
    double r = (2*s)/(a+b+c);
    printf("%f", r);
}

2017/01/25 16:17

코딩초보

import math
def radius(a,b,c):
    S=(a+b+c)/2
    return round(math.sqrt(S*(S-a)*(S-b)*(S-c))/S,3)
radius(12,12,8)

2017/02/19 22:13

김구경

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static java.lang.System.in;

public class TheKnightsOfTheRoundTable {

    public static void main(String[] args) {
        Scanner sc = new Scanner(in);
        List<Double> n = new ArrayList<>();
        n.add(sc.nextDouble());
        n.add(sc.nextDouble());
        n.add(sc.nextDouble());

        Double t = n.stream().reduce((a, b) -> a + b).get();
        Double a = n.stream().max(Double::compareTo).get();
        Double b = n.stream().min(Double::compareTo).get();
        Double c = t - a - b;
        Double d;
        Double r;

        if (a <= t / 2) {
            if (a.equals(c) || b.equals(c)) {
                d = (Math.sqrt(Math.pow(a, 2) - Math.pow(b / 2, 2)) * b) / 2;
                System.out.println(d);
                r = (2 * d) / t;
            } else {
                r = (a - b - c) / 2;
            }
            System.out.printf("The radius of the round table is: %.3f", Math.abs(r));
        } else {
            System.out.println("잘못된 길이");
        }
    }
}

간단한 공식이 있군요 -_-;;

2017/04/03 16:43

genius.choi

import java.util.Scanner;

public class RoundTable {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);

        double a,b,c;//삼각형 세 변의 길이 

        a=s.nextDouble();
        b=s.nextDouble();
        c=s.nextDouble();

        //세 변을 사용해 삼각형 넓이 구함 
        //p=(a+b+c/2)
        //p(p-a)(p-b)(p-c)=(pr)^2
        //r=(p-a)(p-b)(p-c)

        double p=(a+b+c)/2;

        double area=Math.sqrt(p*(p-a)*(p-b)*(p-c));

        double r=area/p;

        System.out.println("The radius of the round table is: "+r);


    }
}

2017/08/03 14:25

김재인

#include<stdio.h>
#include<math.h>

int main()
{
    double side_a, side_b, side_c;      //삼각형의 세 변의 길이를 저장
    double r;                           //내접원의 반지름
    double h;                           //헤론의공식 요소

    do
    {
        printf("삼각형의 세 변의 길이를 입력하시오. >> ");
        scanf("%lf %lf %lf", &side_a, &side_b, &side_c);

        if(side_a >= side_b && side_a >= side_c)            //변 a의 길이가 가장 길 때
        {
            if(side_a < side_b + side_c)                    //삼각형이 성립하는가?
                break;              //Yes
            else
                continue;           //No
        }
        else if(side_b >= side_a && side_b >= side_c)       //변 b의 길이가 가장 길 때
        {
            if(side_b < side_a + side_c)                    //삼각형이 성립하는가?
                break;              //Yes
            else
                continue;           //No
        }
        else                                                //변 b의 길이가 가장 길 때
        {
            if(side_c < side_a + side_b)                    //삼각형이 성립하는가?
                break;              //Yes
        }
    }while(1);                      //No

    h = (side_a + side_b + side_c)/2.0;                             //h : 세 변의 길이의 합의 1/2
    r = sqrt(h * (h - side_a) * (h - side_b) * (h - side_c)) / h;   //헤론의 공식

    printf("가장 큰 원탁의 반지름 : %.3lf\n", r);

    return 0;
}

2017/09/22 13:18

한승엽

import math

while True:
    a,b,c=tuple(map(int, input().split()))
    if max(a,b,c)<=(a+b+c)/2<1e6: break
k=(a+b+c)/2

S=math.sqrt(k*(k-a)*(k-b)*(k-c))
r=S/k
print('The radius of the round table is: {:0.3f}'.format(r))

2017/12/15 05:09

빗나감

파이썬 3.6

  • 삼각형의 내접원(삼각형의 세변에 닿는 최대크기의 원)을 통한 삼각형의 넓이(S) 공식과 혜론의 공식을 이용하여 내접원의 반지름을 구하여 결과를 출력합니다.
import math

def inputdata(casedata):
    case =[]
    try:
        for i in ['a','b','c']:
            i = float(input('%s = '%i))
            case.append(i)
    except ValueError:
        print(" 실수값을 입력해주세요","\n")
        return
    casedata.append(case)
    inputdata(casedata)

def calradius(casedata):
    a,b,c = 0,0,0
    for i in casedata:
        a,b,c= i[0],i[1],i[2]
        s = (a+b+c) / 2
        S = math.sqrt(s*(s-a)*(s-b)*(s-c))
        r = 2*S / (a+b+c)
        print(i," The radius of the round table is: %.3f" %r)

if __name__ == "__main__":
    casedata = []
    inputdata(casedata)
    print("\n")
    calradius(casedata)
  • 결과값
[12.0, 12.0, 8.0]  The radius of the round table is: 2.828

2018/01/10 15:48

justbegin

# 파이썬

sample_input = """12.0 12.0 8.0
7.0 8.0 14.0
4.0 5.0 6.0"""


def round_in_t(triangles):
    triangles = triangles.split("\n")
    for triangle in triangles:
        a, b, c = map(float, triangle.split(" "))
        su = (a+b+c)/2
        r = (su*(su-a)*(su-b)*(su-c))**0.5/su
        print("The radius of the round table is: ", round(r, 3))


round_in_t(sample_input)

2018/02/08 12:29

olclocr

import math
def heron(a, b, c):
    s = (a+b+c)/2
    return math.sqrt((s-a)*(s-b)*(s-c)/s)
while 1:
    n = list(map(float, input().split(' ')))
    if n == [0, 0, 0]:
        break
    print("{0:0.3f}".format(heron(n[0], n[1], n[2])))

2018/02/11 22:12

김동하

텍스트 파일에 12.0 8.0 8.0\n 3.0 4.0 5.0 이렇게 적혀있다고 가정

def triangle_area(a,b,c):
    return (((a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c))**0.5)*0.25

def solve(a,b,c):
    area=triangle_area(a,b,c)
    r=(2*area)/(a+b+c)
    return round(r,3)


f=open(input("파일 주소를 입력하세요(텍스트파일): "))
lines=f.readlines()
for line in lines:
    num_list=line.split(' ')
    new_num_list=[]
    for string in num_list:
        new_num_list.append(float(string))
    r=solve(new_num_list[0],new_num_list[1],new_num_list[2])
    print("The radius of the round table is: %f"%r)

2018/02/19 06:46

D B

import re
import math

def radius(directory) :

    f = open(directory, 'r')
    p = re.compile('(\d+.\d+)\s(\d+.\d+)\s(\d+.\d+)')

    while True :

        values = f.readline()

        if not values :
            break

        else :
            m = p.match(values)
            addition = float(m.group(1))+float(m.group(2))+float(m.group(3))
            r = (2/addition)*math.sqrt((addition/2)*(addition/2-float(m.group(1)))*(addition/2-float(m.group(2)))*(addition/2-float(m.group(3))))
            print('The radius of the round table is : %0.3f' %r )

.txt 형식으로 데이터가 입력된다고 가정하고 진행했습니다.

2018/03/10 16:22

박강민

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] str = br.readLine().split(" ");
        int[] nums = new int[3];
        for(int i=0; i<3; i++) {
            nums[i] = Integer.parseInt(str[i]);
        }
        int s = (nums[0] + nums[1] + nums[2])/2;
        int a1 = s-nums[0];
        int b1 = s-nums[1];
        int c1 = s-nums[2];
        float sum = nums[0] + nums[1] + nums[2];
        System.out.printf("%.3f",2*Math.sqrt(s*a1*b1*c1)/sum);
    } // 파일끝에 다다른다는 게 먼소린지 이해불가

2018/05/04 12:33

정몽준

def author():
    mystr = input("Please insert the test case : " )
    mylist = mystr.split(",")
    while len(mystr) != 0 :
        a,b,c = int(mylist[0]),int(mylist[1]),int(mylist[2])
        if max(a,b,c) > (a+b+c)/2 :
            print("your input is invalid")
        else:
            s = (a+b+c) / 2
            area = (s*(s-a)*(s-b)*(s-c))**(1/2)
            r = (2*area) / (a+b+c)
            print("The radius of the round table is: {}".format(round(r,3)))
        mystr = input("Please insert another test case : ")
        mylist = mystr.split(",")
    print("Good Bye~")

2018/05/09 13:08

yijeong

while True:
    x = list(map(int, input('Please enter the lengths of 3 side of triangle(ex : 4 5 8) : ').split()))
    if not x: break
    if len(x) != 3 or max(x) > sum(x)/2 or 0 in x: print('Wrong input data')
    else:
        s, a, b, c = sum(x)/2, x[0], x[1], x[2]
        r = ((s-a)*(s-b)*(s-c) / s)**0.5
        print('The radius of the round table is: %.3f' % r)

2018/05/09 23:11

Hyuk

public class RoundTable {
    public static void main(String[] args) {
        double a, b, c;

        Scanner sc = new Scanner(System.in);
        while(true) {
            a = sc.nextDouble();
            b = sc.nextDouble();
            c = sc.nextDouble();
            sc.nextLine();

            if(a < 0.0000000d || b < 0.0000000d || c < 0.0000000d ||
                    a >= 1000000d || b >= 1000000d || c >= 1000000d)
                return;

            double s = (a + b + c) / 2;
            double r = Math.sqrt(s * (s - a) * (s - b) * (s - c)) / s;

            System.out.println("The radius of the round table is: " + (Math.round(r * 1000) / 1000d));
        }
    }
}

2018/05/21 17:08

배혁남

Python

import math
a = 12.0
b = 12.0
c = 8.0

s = (a+b+c)/2
S = math.sqrt(s*(s-a)*(s-b)*(s-c))
r = S/s
print("{0:.3f}".format(r))

2018/06/07 14:49

Taesoo Kim

import math
data = "12.0 12.0 8.0"
for d in data.split('\n'):
    a, b, c = map(float,d.split())
    # 헤론의 공식: 삼각형의 넓이 
    s = (a + b + c)/2
    A = math.sqrt((s-a)*(s-b)*(s-c)*s)
    # 반지름 구하기
    r = 2*A/(a+b+c)
    print(round(r, 3))

2018/07/04 21:37

재즐보프

a,b,c = 12,12,8

r = b * (a**2 - (a**2+b**2-c**2)**2 /(4*(b**2)))**0.5 /(a+b+c)
print(r)

수학으로 푸는게 아니라
수치해석으로 좌표를 수렴시켜 보라는 문제인듯 한데....귀찮아서 그냥 연습장에 끄적끄적 유도했습니다;;;

2018/07/19 21:41

Creator

import math
a=float(input('삼각형의 한 변의 길이를 입력:'))
b=float(input('삼각형의 한 변의 길이를 입력:'))
c=float(input('삼각형의 한 변의 길이를 입력:'))

area1=0.5*a*b*(math.sqrt(1-((a**2+b**2-c**2)/(2*a*b))**2)) # 헤론의 공식
radi=float((area1*2)/(a+b+c)) #내접 반지름 구하기
print("radius= ", round(radi,3))

2018/08/08 15:51

S.H

(a, b, c) = (3, 4, 5)
Peri = a + b + c

def sqrt(a):
    ip = 0
    deci_len = int(input("How many decimal do you want?"))

    while (ip + 1) ** 2 <= a:
        ip = ip + 1

    deci_list = list()
    i = 1
    approx = ip

    while i <= deci_len:
        deci_dyn = 0
        stck = 0.1 ** i
        while (approx + stck) ** 2 <= a:
            deci_dyn = deci_dyn + stck
            approx = approx + stck
        deci_list.append(deci_dyn)
        i = i + 1

    approx_list = ip
    for j in deci_list:
        approx_list = approx_list + j

    return approx_list


S = sqrt(Peri)
r = 2 * S / Peri

print("The radius of the round tavle is:", r)

print(sqrt(3))

저는 python을 사용하였습니다. 메서드를 import 하지 않고 직접 sqrt()를 만들어 보았어요~ 근데 실수를 계속 해서 너무 오래 걸렸네요ㅜㅜ 마지막 줄은 제 함수가 제대로 작동하는지 시험해 본 것입니다

2018/08/22 02:39

aa

import math a = float(input("Triangle first : ")) b = float(input("Triangle second : ")) c = float(input("Triangle third : "))

s = (a + b + c) / 2 S = math.sqrt(s(s-a)(s-b)*(s-c)) r = S/s print("{0:.3f}".format(r))

2018/09/10 18:46

문승현

세 변의 길이가 a, b, c인 삼각형과 반지름이 r인 내접원이 주어졌을 때, 삼각형의 면적(Area)은

[1] Heron's Formula:

Area = Sqrt{s(s-a)(s-b)(s-c)}

[2] 내접원과 삼각형 면적의 관계:

Area = rs

여기서,

s = (a+b+c)/2

따라서, 내접원의 반지름은

r = Sqrt{s(s-a)(s-b)(s-c)} / s

C#

using System;
using System.Linq;
using System.IO;

namespace CD055
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] inputs = File.ReadAllLines(@"C:\Temp\CD055Input.txt");
            foreach (var input in inputs)
            {
                ParseInput(input, out double a, out double b, out double c);
                Console.WriteLine($"The radius of the round table is: {Radius(a, b, c)}");
            }
        }

        static double Radius(double a, double b, double c)
        {
            double s = (a + b + c) / 2;
            return Math.Round((Math.Sqrt(s * (s - a) * (s - b) * (s - c)) / s), 3);
        }

        static void ParseInput(string aString, out double a, out double b, out double c)
        {
            double[] parsedData = aString.Split(',').Select(s => double.Parse(s)).ToArray();
            a = parsedData[0]; b = parsedData[1]; c = parsedData[2];
        }
    }
}

2018/09/13 11:23

mohenjo

코딩보다 내접원과 넓이 관계 찾아보고 이해하는게 더 어려웠던거같아요! 댓글보니까 파일을 불러와서 쭉 풀어내는 문제같길래 파일 불러오기로 했습니다

def radius(file):
    f = open(file)
    triangles = f.readlines()
    for triangle in triangles:
        sides = triangle.split()
        (a,b,c) = (float(sides[0]),float(sides[1]), float(sides[2]))
        s = (a+b+c) / 2
        size = (s * (s-a) * (s-b) * (s-c)) ** 0.5
        r = round(size / s, 3)
        print("The radius of the round table is: %s" % r)

2018/09/26 12:45

윤종석

import math

a = float(input('첫번째 변의 길이는?'))
b = float(input('두번째 변의 길이는?'))
c = float(input('세번째 변의 길이는?'))

if a>1000000 or b>1000000 or c>1000000:
    print("\n최대 길이 초과 입니다")
    exit()
else:
    s = (a +b +c)/2.0
    S = math.sqrt(s*(s-a)*(s-b)*(s-c))
    r = 2.0*S/(a+b+c)

print("The radius of the round table is: %.3f" %r)

2018/10/04 02:17

농창

#include <stdio.h>
#include <math.h>
double _Area(double side1, double side2,double side3);

int main()
{

    double side1;
    double side2;
    double side3;
    double Area;
    double Radius;

    scanf_s("%lf %lf %lf", &side1, &side2, &side3);
    Area = _Area(side1, side2, side3);

    if (side1, side2, side3 < 1000000 && side1, side2, side3 <= (side1 + side2 + side3) / 2) 
    {

        Radius = (2 * Area)/(side1 + side2 + side3);

        printf("The radius of the round table is : %.3f.", Radius);
    }
    else
        printf("변의 길이가 너무 큽니다 \a");

    return 0;
}

double _Area(double side1,double side2,double side3)
{
    double s;
    double Calculate;

    s = (side1 + side2 + side3) / 2;

    Calculate = sqrt(s*(s - side1)*(s - side2)*(s - side3));

    return Calculate;
}

2018/10/16 09:07

이호인

def f5(a,b,c):
    s = (a+b+c)/2
    r = ((s*(s-a)*(s-b)*(s-c))**(1/2))/s
    return round(r,3)

2018/11/05 20:26

dodoman

# python 3.7.1

with open("SampleInput.txt") as f:
    for text in f.readlines():
        a, b, c = map(float, text.split(" "))
        if max(a, b, c) > 1000000 or max(a, b, c) > (a + b + c)/2:
            continue

        s = (a + b + c) / 2
        r = ((s - a) * (s - b) * (s - c) / s) ** 0.5
        print("The radius of the round table is:", round(r, 3))

2018/11/21 10:46

정지환

자바입니다...좀 엉망입니다...

import java.io.*;
import java.util.*;
import java.math.*;

public class Animal{
    public static void main(String args[])
    {
        Scanner scanf = new Scanner(System.in);
        float r1, r2, r3; 
        double result,result2;

        System.out.print("Put your 1st number: ");
        r1 = scanf.nextFloat();
        System.out.print("Put your 2nd number: ");
        r2 = scanf.nextFloat();
        System.out.print("Put your 3rd number: ");
        r3 = scanf.nextFloat();

        result = (r1 + r2 + r3)/2;
        result2 = Math.sqrt((result-r1)*(result-r2)*(result-r3)/result);

        System.out.print("The radius of the round table is: "+ Math.round(result2*1000)/1000.0);    
    }   
}

2018/11/21 15:20

dbnfqe

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

/*
Example
삼각형의 세 변의 길이가 각각 4
4
, 4
4
, 6
6
일 때 삼각형의 넓이를 구하여라.

Answer
세 변 길이의 합의 절반인 s
s
를 먼저 구합니다.


s=
4+4+6
2
=7
s=4+4+62=7


삼각형의 넓이 S
S
는 다음과 같습니다.


S=√7(7−4)(7−4)(7−6)=3√7
S=7(7−4)(7−4)(7−6)=37
*/
int main()
{
    double result=0;
    double num1,num2,num3;
    double s=0;
    scanf("%lf %lf %lf",&num1,&num2,&num3);
    s=(num1+num2+num3)/2;
    result=sqrt(s*(s-num1)*(s-num2)*(s-num3));
    result=2*result / (num1+num2+num3);
    printf("%.3f\n",result);
    return 0;
}

헤론공식... 수학다시해야겠네요.. 다까먹..

2018/11/25 00:09

김범준

import math

side = input("삼각형의 세 변의 길이 : ").split(" ")
sum = 0

for i in side:
    sum += int(i)

s = sum * 0.5
S = math.sqrt(s*(s-int(side[0]))*(s-int(side[1]))*(s-int(side[2])))

r = round(S / s, 3)

print("The radius of the round table is : %f" % r)

2018/12/16 13:47

김명규

import math
import types

def isNumber(val):
    return True if isinstance(val, types.IntType) or isinstance(val, types.FloatType) else False

def calculate_inradius(a, b, c):
    if not isNumber(a) or not isNumber(b) or not isNumber(c):
        print "Wrong type"
        return 0

    s = (a+b+c) * .5
    radius = 0
    try:
        radius = math.sqrt((s-a)*(s-b)*(s-c) / s)
    except ZeroDivisionError:
        print "Divide by zero"
    radius = round(radius, 3)
    return radius

if __name__ == '__main__':
    with open('input.txt', 'r') as f:
        for line in f:
            a, b, c = map(float, line.split())
            print "The radius of the round table is: " + str(calculate_inradius(a, b, c))

2018/12/20 04:05

RumbleBang

# Python3.7.2

while 1:
    inp = input("\nWhat are the lengths of the three sides of the triangle? ")
    data = list(map(float,inp.split()))
    if len(data) != 3:
        print("\nThe number of triangle sides is 3. You entered %d numbers." % len(data))
    else:
        if max(data) < sum(data)-max(data):
            break
        else:
            print("\nThe longest side of a triangle is shorter than the sum of the others.")

s = sum(data)/2
S = (s*(s-data.pop())*(s-data.pop())*(s-data.pop()))**0.5
r = S/s
print("The radius of the round table is: %s." % round(r,3))


입력 값들이 잘못 되면 내용을 알려주고 다시 입력값을 넣도록 메세지를 보여주는 부분을 포함해 보았습니다.

2019/01/01 15:44

돌구늬ㅋ~썬

import math

input = input()

ThreeSides = list(map(float, input))

a = ThreeSides[0]
b = ThreeSides[1]
c = ThreeSides[2]

s = (a + b+ c) / 2

heron = math.sqrt(s*(s-a)*(s-b)*(s-c))

r = heron / s

print("The radius is %f." %r)

2019/01/03 13:03

Woohyuck Choi

list_ = list(map(float, input("삼각형의 세 변의 길이를 입력 : ").split()))

while (sorted(list_)[0] + sorted(list_)[1]) <= sorted(list_)[2] :
# 삼각형의 결정 조건: 가장 긴 변의 길이 < 나머지 두 변의 길이의 합
    print("삼각형의 결정 조건을 만족하지 못합니다")
    list_ = list(map(float, input("삼각형의 세 변의 길이를 입력 : ").split()))

a, b, c = sorted(list_)

from math import sqrt

S = (sqrt((a+b+c)*(a+b-c)*(b+c-a)*(c+a-b))) / 4
# 삼각형의 넓이 공식(헤론의 공식)

r = (2*S) / (a+b+c)
# 삼각형 내심원의 반지름을 구하는 공식

print(round(r,3))

2019/01/03 22:14

lucky1to10

```{.python} from math import *

while True: in= input() if in.split(' ') !=3: break a,b,c=map(float, in.split(' ')) s=(a+b+c)*1/2 heron=sqrt(s(s-a)(s-b)(s-c)) r= heron/s print("The radius of the table is:" , round(r,3)) ```from math import *

while True: in= input() if in.split(' ') !=3: break a,b,c=map(float, in.split(' ')) s=(a+b+c)*1/2 heron=sqrt(s(s-a)(s-b)(s-c)) r= heron/s print("The radius of the table is:" , round(r,3))

2019/01/11 22:48

jj kim

from math import sqrt

def inscir(a,b,c):
    s = (a+b+c)/2
    return int(sqrt(((s-a)*(s-b)*(s-c))/s)*1000)/1000

위키백과에서 헤론의 공식을 참조했습니다

2019/01/13 14:48

김영성

import math

a, b, c = map(float, input().split())
s = (a + b + c) / 2
S = math.sqrt(s * (s-a) * (s-b) * (s-c))
r= S / s
print("The radius of the round table is: {0:.3f}".format(r))

2019/01/14 13:59

D.H.

def Round_Table(a, b, c):
    if max(a, b, c) >= min(a, b, c) + ((a + b + c) - max(a, b, c) - min(a, b, c)):  #삼각형의 조건
        print("That's not a triangle.")
    else:
        r = ((a + b -c)*(a - b + c)*(-a + b + c)/(a+ b+ c)**0.5) / 2                #헤론의 공식
    return "The radius of the round table is: %d" % r


first, second, third = (input("세 변의 길이 : ").split(' '))                  
print(Round_Table(int(first), int(second), int(third)))                            

2019/01/28 11:06

손태호

import math
a, b, c = list(map(float, input().split()))
if max(a,b,c) <= (a+b+c)/2:
    s = (a+b+c)/2
    S = math.sqrt(s * (s-a) * (s-b) * (s-c))

    r = 2 * S / (a+b+c)

    print("The radius of the round table is : ", r)

어떻게 나왔는지 설명해드리죠. 먼저, s! s = (a+b+c)/2 이게 삼각형이 만들어지는 조건이라고 하는데, if문에서 보시면 max라는 함수를 이용해서 사용하는 방법이 있습니다. 만약 이게 s가 더 작게 되면 이렇게 될 가능성이 있습니다. 뭐 이건 누구나 초등학생 수준의 아이디어이니까 다들 아시겠죠?

그 다음, S! S는 헤론의 공식을 이용해서 삼각형의 넓이를 구할 수 있다고 합니다. 그리고 헤론의 공식은 함부로 허수라는 값을 나올 수 없게 만들었기 때문에 문제에서 주어진 조건이 나온 것입니다.

마지막으로 원의 둘레의 길이 : 수식으로 정리하자면 지금 여기서는 어떻게 작성해야 할지... 일단 여러분은 이미 알고 계실 거라고 저는 믿고 있습니다.

2019/02/06 19:21

조재현

python 3.7

import math
side=list(map(float,input().split()))
try:
    s=(side[0]+side[1]+side[2])/2
    a=math.sqrt(s*(s-side[0])*(s-side[1])*(s-side[2]))
    r=a*2/(side[0]+side[1]+side[2])
    print('%.4g' %r)
except IndexError :
    print("indexing error") 
except :
    print("error")

2019/02/09 22:43

Changmin Mun

import math
f=open("./table_len.txt", 'r') # 삼각형 길이가 적힌 파일 table_len.txt 오픈
lines = f.readlines()
f.close()
for line in lines:
    a, b, c = line.split()
    a = float(a)
    b = float(b)
    c = float(c)
    s = (a+b+c)/2
    before_sqrt = (s-a)*(s-b)*(s-c)/s
    r = math.sqrt(before_sqrt)
    f=open("./radius_of_the_table.txt",'a')  # 원 반지름 파일을 열어 추가로 작성
    round_table = """The radius of the round table is : """+"{0:0.3f}".format(r)+"\n"
    f.write(str(round_table))
    f.close()

2019/02/14 11:49

김상민

input_data = []
while 1:
    txt = input()
    if txt == '':
        break
    else:
        input_data.append(txt)
r = []
for items in input_data:
    a, b, c = map(float, items.split(' '))
    s = (a+b+c)/2
    heron = sqrt(s*(s-a)*(s-b)*(s-c))
    print('The radius of the round table is :', round(heron/s, 3))

2019/02/18 11:57

이지혜

while True:
    lengths=input("Input lengths of sides of the triangle, seperate them with space: ")
    [a,b,c]=[float(x) for x in lengths.split()]
    s=(a+b+c)/2
    area=(s*(s-a)*(s-b)*(s-c))**0.5
    radius=area/s
    print("The radius of the round table is: {:.3f}".format(radius))    

2019/02/24 23:24

ykleeac

import math

n=(input(' enter : ')) l=(n.split(' '))

a=float(l[0]) b=float(l[1]) c=float(l[2])

s=(a+b+c)/2 p=((s-a)(s-b)(s-c))/s r=math.sqrt(p)

print('The radius of the round table is: %.3f'%r)

2019/03/09 10:17

Fiesta

#include <stdio.h>
#include <math.h>

float output(float a, float b, float c);

int main() {
    float a, b, c;
    float max = 0;
    float sum = 0;

    while (1) {
        scanf("%f %f %f", &a, &b, &c);
        sum = a + b + c;

        if (a > b)
            max = a;
        else
            max = b;

        if (c > max)
            max = c;

        if (sum - max > max)
            printf("The radius of the round table is: %.3f\n", output(a, b, c));
        else
            printf("Triangle does not form\n");
    }
}

float output(float a, float b, float c) {
    float s = (a + b + c) / 2;
    float r;

    r = (2 * sqrt(s*(s - a)*(s - b)*(s - c))) / (a + b + c);

    return r;
}

c로 풀어봤습니다.

2019/03/12 17:27

황정인

mport math

def rad(a, b, c):
    if (max(a, b, c) < 1000000) and (max(a,b,c) <= (a+b+c)/2):
        """ S = sqrt(s(s-a)(s-b)(s-c)) = 1/2 * r * (a+b+c) = s * r, s= a+b+c/2"""
        s = (a+b+c)/2
        S = math.sqrt(s*(s - a)*(s - b)*(s - c))
        return S/s

with open('input.txt','r') as file:
    for line in file:
        line = line.split()
        a = float(line[0])
        b = float(line[1])
        c = float(line[2])

        radi = rad(a, b, c)
        print('The radius of the round table is: ', round(radi, 3))

2019/04/09 21:55

Hwaseong Nam

헤론의 공식 이용

import math
def round_table(a, b, c):
    s= (a+b+c)/2
    result = math.sqrt(((s-a)*(s-b)*(s-c))/s)
    return round(result,3)

if __name__=='__main__':
    while True :        
        point = input('삼각형 세 변의 길이를 입력하세요. (종료 : q)')
        if point == 'q':
            break
        point = point.split()
        point = list(map(float, point))
        if max(point)>(point[0]+point[1]+point[2])/2 :
            print('세 변의 길이가 잘못되었습니다.')
        else :
            result = round_table(point[0], point[1], point[2])
            print(f'The radius of the round table is: {result}')

2019/04/16 20:49

쨔이

def radious_in(q,w,e): L=(q+w+e)/2 if max(q,w,e) >L: exit() elif q>1000000 or w>1000000 or w>1000000: exit()

A=(L*(L-q)*(L-w)*(L-e))**0.5
return A/L

a,b,c= map(float,input().split())

print("The radius of the round table is: {}".format(round(radious_in(a,b,c),3)))

2019/04/30 14:31

암살자까마귀

python3.6 입니다.

f = open('/workspace/CodingDojang/Level1/The_Knights_Of_The_Round_Table/input.txt', 'r')

while True:
    datum = f.readline()
    if datum == '':
        break
    a, b, c = map(float, datum.strip().split(' '))
    s = (a+b+c)/2
    area = (s*(s-a)*(s-b)*(s-c))**(0.5)
    r = area/s
    print('The radius of the round table is: %.3f   (input : %s %s %s)' % (round(r, 3), a, b ,c))

f.close()

2019/05/17 19:28

최상혁

s = (a + b + c) / 2;
cout << "The radius of the round table is: " << sqrtf((s-a)*(s-b)*(s-c)/s) << endl;

2019/07/02 15:32

캐니

#the Knights of the round table
f = open("triangle.txt",'w')
data = "12 12 8\n5 5 9"
f.write(data)
f.close()

f = open("triangle.txt",'r')
while True:
    line = f.readline()
    if not line:
        break
    else:
        linelist= line.split()
        print(linelist)
        a=int(linelist[0])
        b=int(linelist[1])
        c=int(linelist[2])
        s = (a+b+c)/2
        r=((s*(s-a)*(s-b)*(s-c))**0.5)*2/(a+b+c)
        print("반지름의 길이: %0.3f" %r)
f.close()

2019/07/24 18:25

김다희

a = input().split(' ')
length_0 = int(a[0]); length_1 = int(a[1]); length_2 = int(a[2])
p = float((length_0 + length_1 + length_2)/2)
area = (p*((p - length_0)*(p - length_1)*(p - length_2))) ** 0.5
r = (area * 2) / (length_0 + length_1 + length_2)
print('%.3f'% r)

2019/08/16 18:39

이명운

import math
X = list(map(float, input().split()))
s = (X[0] + X[1] + X[2])/2
A = math.sqrt(s*(s - X[0])*(s - X[1])*(s - X[2]))
r = A/s
print("The radius of the round table is: %.3f" %(round(r, 3)))

2019/09/03 23:43

철쇄아

헤롯의 공식으로 푸신 분 풀이 보고 참고했습니다.

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print(">> 삼각형의 첫번째 변을 입력하세요 : ");
    double a = sc.nextDouble();
    System.out.print(">> 삼각형의 두번째 변을 입력하세요 : ");
    double b = sc.nextDouble();
    System.out.print(">> 삼각형의 세번째 변을 입력하세요 : ");
    double c = sc.nextDouble();

    double s = (a+b+c)/2;
    double S = Math.sqrt(s*(s-a)*(s-b)*(s-c));

    //S = (1/2)*(a+b+c)*r
    //r = S*2/(a+b+C)

    double r = 2 * S / (a+b+c);

    System.out.println("The radius of the round table is: "+Math.round(r*1000)/1000.0);


    sc.close(); 

2019/09/09 15:43

yeeun shim

a = input("a:") b = input("b:") c = input("c:") r = (((-a+b+c)(a-b+c)(a+b-c)/(a+b+c))**0.5)/2 print "r :%d" %(r)

2019/09/21 18:53

김민규

import math

a = float(input("A 값 : "))
b = float(input("B 값 : "))
c = float(input("C 값 : "))
max_value = 0
if a and b and c < 1000000:
    if max(a,b,c) <= (a+b+c)/2:
        s=(a+b+c)/2                  #헤론의 공식
        ss= math.sqrt(s*(s-a)*(s-b)*(s-c))
        r=2*ss/(a+b+c)
        result = round(r,3)
        if max_value < result:
            max_value = result

print("The radius of the round table is : ",max_value)

2019/10/02 18:49

semipooh

package practiceLv1;
import java.util.Scanner;
public class TheKnightsOfTheRoundTable {
double a,b,c;
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double a = scan.nextDouble();
        double b = scan.nextDouble();
        double c = scan.nextDouble();
        if(a>1000000||b>1000000||c>1000000) {
            System.out.println("세변의 길이를 다시 입력해주세요!!");
        }
        //S=1/2 (a+b+c)r  내접원의 반지름 구하는 공식
        double s = (a+b+c)/2;
        double S = Math.sqrt(s*((s-a)*(s-b)*(s-c)));
        System.out.println("The radius of the round table is: "+ S*2/(a+b+c));

    }

}

2019/11/07 21:50

big Ko

import math

a = int(input("Length of a:"))

b = int(input("Length of b:"))

c = int(input("Length of c:"))

if a < 1000000 and b <1000000 and c<1000000 and max(a,b,c)<= (a+b+c)/2 :

s = (a+b+c)/2

S = math.sqrt(s*(s-a)*(s-b)*(s-c))

r = (2*S)/(a+b+c)

print ("The radius of the rounf table is:",round(r,3))

else : print("Correct Length, please")

2019/12/28 13:52

HyukHoon Kim

while True:
    n=list(map(float,input("삼각형의 세 변의 길이를 입력하십시오: ").split(",")))
    # 삼각형이 되지 않는 조건 설정(변의 개수가 3개가 아니거나 어떤 두 변의 합이 나머지 한 변보다 항상 커야한다)
    if not (len(n)==3 and n[0]+n[1]>n[2] and n[1]+n[2]>n[0] and n[2]+n[0]>n[1]):
        print("삼각형이 아닙니다.")
        break
    s=0
    for k in n:
        s+=k/2
    sq=(s*(s-n[0])*(s-n[1])*(s-n[2]))**(1/2)
    r=2*sq/sum(n)
    print(n[0],n[1],n[2])
    print("The radius of the round table is:", round(r,3))

2019/12/30 19:09

박시원

from math import *

while True: inp = input() if len(inp.split()) != 3: break a,b,c = map(float,inp.split()) s = (a+b+c)/2 heron = sqrt(s(s-a)(s-b)*(s-c)) r = heron/s # 1/s = 2/(a+b+c) print('The radius of the round table is: {0:.3f}'.format(r))

앞전에 하신 분들 코딩들 중 하나를 공부한 다음에 그 코딩 그대로 올렸습니다. 헤론의 공식을 이번에 처음 알았네요..

2020/02/06 16:28

이국성

파이썬

제약조건을 안보고 풀어서 에러까지 함께 코딩했습니다.

from math import sqrt

def get_maximum_radius(input):
    if (sum(input)<2*max(input)):
        raise ValueError
    elif max(input)>1000000 or min(input) <=0:
        raise IndexError
    else:
        s=sum(input)/2
        return round(sqrt((s-input[0])*(s-input[1])*(s-input[2])/s),3)

input=[12,8,12] # put input here!

try:
    print(get_maximum_radius(input))
except ValueError:
    print('삼각형이 형성될 수 없는 값입니다.')
except IndexError:
    print('인풋이 잘못되었습니다. 0~1000000 사이의 3개 값을 넣어주세요.')


>>2.828

2020/02/10 10:13

지창현

파이썬 3.8

import math


threeline = []
while len(threeline) != 3:
    if len(threeline) == 0:
        inp = input("세 변의 길이를 입력하세요\n")
        threeline.extend(inp.split())
        continue

    elif len(threeline) == 1:
        inp = input("두 변의 길이를 더 입력하세요\n")
        threeline.extend(inp.split())
        continue

    elif len(threeline) == 2:
        inp = input("한 변의 길이를 마저 입력하세요\n")
        threeline.extend(inp.split())
        continue

    else:
        print("너무 많이 입력하셨습니다. 처음부터 다시 입력해주세요")
        threeline = []
        continue
a, b, c = map(float, threeline)
s = (a+b+c)/2                       #  using heron's formula
S = math.sqrt(s*(s-a)*(s-b)*(s-c))  #  ussing heron's formula
r = S/s                             #  1/2 * (세변의길이의합(s)) * r = 삼각형의 넓이(S)
print("The radius of the round table is: %.3f" % r)

2020/02/24 18:47

우제훈

a = int(input("input a  "))
b = int(input("input b  "))
c = int(input("input c  "))
s = (a + b + c) / 2
A = ((s * (s - a) * (s - b) * (s - c)) ** (1 / 2) / s) * 1000
print("The radius of the round table is:", int(A) / 1000)

2020/03/05 13:49

from math import *
inp = input()          
def tri(string):
    a,b,c= list(map(float,string.split()))
    s= (a+b+c)/2
    if max(a,b,c)<=1000000 and max(a,b,c)<=s:
        heron = sqrt(s*(s-a)*(s-b)*(s-c))
        r = heron/s
        return 'The radius of the round table is: %0.3f'%r 
print(tri(inp))

2020/03/05 16:27

황예진

a, b, c=input().split() a=float(a) b=float(b) c=float(c) s= (a+b+c)/2 R=((s(s-a)(s-b)(s-c))*0.5)/s print(round(R,3))

2020/03/06 13:21

sotmef222

tri = input("삼각형 세변의 길이:")
a,b,c = eval(tri)


def radius(a,b,c):
    s = (a+b+c)/2
    r = ((s-a)*(s-b)*(s-c)/s)**0.5
    result = "{:.3f}".format(r)
    return result


print(radius(a,b,c))

2020/03/15 14:12

장래희망코인물

a = float(input('a의 길이를 입력하시오:'))
b = float(input('b의 길이를 입력하시오:'))
c = float(input('c의 길이를 입력하시오:'))
if a+b>c and b+c>a and c+a>b :
    s = (a+b+c)/2
    r = ((s*(s-a)*(s-b)*(s-c))**0.5)/s
    print("반지름의 값은 %0.3f 입니다" %r)
else : print("삼각형이 아닙니다")

2020/03/17 14:33

신지환

import math

print('삼각형의 세 변의 길이를 입력하시오')
_data = input()
_tri = _data.split()
a = float(_tri[0])
b = float(_tri[1])
c = float(_tri[2])
s = (a+b+c)/2
_tri_area = math.sqrt(s*(s-a)*(s-b)*(s-c))
_cir_r = (2*_tri_area)/(a+b+c)
print(f'원형 탁자의 반지름은 {_cir_r:0.3f}입니다.')

공식을 몰라서 한참 고민했습니다.

2020/03/25 00:59

기둘비

삼각형 변의 길이로 삼각형 넓이 구하는 것(헤론의 공식)과 내접원의 반지름을 통한 삼각형넓이 구하는 공식을 이용하였습니다

while True:
    try:
        a, b, c = map(float, input('삼각형 각변의 길이를 입력하세요(변의길이가 0이하니 경우 종료): ').split())
    except Exception as ex:
        print('종료합니다')
        break

    if min(a, b, c) <= 0:
        print('종료합니다')
        break

    if max(a, b, c) <= (a + b + c) / 2 and max(a, b, c) <= 1000000: # 제약조건 2개 만족여부 확인
        s = (a + b + c) / 2
        heron_s = (s * (s-a) * (s-b) * (s-c))**0.5  # 헤론의 공식: sqrt(s*(s-a)*(s-b)*(s-c))  단, s=(a+b+c)/2 
        r = 2 * heron_s / (a+b+c)                  # 삼각형 내접원 반지름 이용 삼각형 넒이 구하는 공식:  (a+b+c)/2*r
        print('the radius of the round table is {:.3f}'.format(r))
    else:
        print('삼각형 변의 길이가 제약조건에 맞지 않습니다')
        break

2020/04/04 10:21

잘해보자

import sys
import math
a,b,c=map(int,input("세 변을 입력하세요 : ").split())
if max(a,b,c)>(a+b+c)/2 :
    sys.exit()
s=(a+b+c)/2
S=math.sqrt(s*(s-a)*(s-b)*(s-c))
result = (2*S)/(a+b+c)
print('The radius of the round table is : %.3f' %result)

2020/04/09 11:04

조윤재

def tri(a,b,c):

    import math



    s=(a+b+c)/2
    ss=math.sqrt(s*(s-a)*(s-b)*(s-c))
    print('창문 면적은 : ',ss)
    r=ss/s
    print('원탁 반경은 : ',r)

2020/04/09 21:07

양양짹짹

import math

triangle1=12.0
triangle2=12.0
triangle3=8.0

s=(triangle1+triangle2+triangle3)/2
t1=s-triangle1
t2=s-triangle2
t3=s-triangle3
ma=s*t1*t2*t3
area=math.sqrt(ma)
#area=1/2(a+bc)*r = 2area=(a+b+c)r = 2area/(a+b+c)=r
r=(area*2)/(triangle1+triangle2+triangle3)

print("The radius of the round table is: {0:.3f}".format(r))

사실상 수학문제......... 수학 배운거 다 까먹어서 헤론의 공식과 삼각형의 내접원의 반지름 구하는 방법 알아내는데 대부분의 시간을 소모

2020/04/10 10:54

yhpdoit

import java.util.Scanner;

public class Q055 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double a,b,c,r;

        while(true) {
            a = scan.nextDouble();
            b = scan.nextDouble();
            c = scan.nextDouble();
            scan.nextLine();

            double s = (a + b + c) / 2;
            r = Math.sqrt(s * (s - a) * (s - b) * (s - c)) / s;
            System.out.println("The radius of the round table is: " + (Math.round(r * 1000) / 1000d));

        }
    }
}

java

2020/05/03 13:52

Daniel Park

import math

a,b,c = int(input()),int(input()),int(input())

if max(a,b,c) <= (a+b+c)/2:
    s = (a+b+c)/2
    S = math.sqrt(s * (s-a) * (s-b) * (s-c))
    r = round(2 * S / (a+b+c),3)
    result = "The radius of the round table is: %r"%r
else:
    print("에러임")

print(result)

2020/05/06 23:55

Money_Coding

from math import *

a, b, c = input('삼각형의 세 변의 길이를 입력하세요: ').split()
a = float(a)
b = float(b)
c = float(c)
s = (a + b + c)/2
H = sqrt(s*(s - a)*(s - b)*(s - c))
r = H/s
print('The radius of the round table is:', round(r,3))

2020/05/14 14:47

재미있는영상어디없나

import math
#파이썬
slides = list(map(float,input().split())) #각 변의 개수 입력
s = 0

for i in range(0,len(slides),3): #변의 개수를 3개씩 끊기 위해 0부터 변의 개수보다 작을 때 까지 3씩 증가
    s = sum(slides[i:i+3])/2 #헤론의 공식 사용을 위해 (3개 변의 합/2)를 구함
    #width = (헤론의 공식에 의한 삼각형의 넓이)
    #(s*r) = 삼각형의 넓이에서, s*r = width 이므로, r = width/s
    width = math.sqrt(s*(s-slides[i])*(s-slides[i+1])*(s-slides[i+2])) 
    r = width/s

    print('The radius of the round table is : %.3f'%r)

2020/05/18 00:24

맛나호두

'''
s = (a+b+c)/2,
S = sqrt( s(s-a)(s-b)(s-c) ) = 1/2 * r * (a+b+c) = s * r
=> r = S / s
'''

def run(a, b, c):
    s = (a + b + c) / 2
    S = (s * (s - a) * (s - b) * (s - c)) ** 0.5
    r = S / s
    return round(r, 3)

print("The radius of the round table is: ", run(12.0, 12.0, 8.0))

2020/09/07 00:05

BigMango

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

int main (void){

    double a,b,c,s;
    while(1){
        while(1){
            printf("a:");
            scanf("%lf",&a);
            if(a>0&&a<=1000000)
                break;
            else{
                printf("다시 입력해 주세요");
                system("cls");
        }
    }
        while(1){
            printf("b:");
            scanf("%lf",&b);
            if(b>0&&b<=1000000)
                break;
            else{
                printf("다시 입력해 주세요");
                system("cls");
                printf("a:%lf\n",a);
            }
        }
        while(1){
            printf("c:");
            scanf("%lf",&c);
            if(c>0&&c<=1000000)
                break;
            else{
                printf("다시 입력해 주세요");
                system("cls");
                printf("a:%lf b:%lf\n",a,b);
            }
        }
        if(a<=b+c&&b<=c+a&&c<a+b)
            break;
        else
        {
            printf("다시 입력해 주세요\n");
            system("cls");
        }
    }
    s=(a+b+c)/2;
    s=sqrt(s*(s-a)*(s-b)*(s-c));
    s=2*s/(a+b+c);
    printf("The radius of the round table is: %.3lf",s);
}
return 0;
}

C언어- 모든 조건을 판정하니깐 길어지네요

2020/09/12 22:31

June

def heron(a, b, c):
    s = (a+b+c)/2
    return ((s-a)*(s-b)*(s-c)/s)**(0.5)

a,b,c = map(float,input().split())

if max(a, b, c) >= min(a,b,c) + (a+b+c-max(a,b,c)-min(a,b,c) or max(a,b,c)>=1000000):
    print("That's not a triangle")
else:
    print("The radius of the round table is :" + str(heron(a,b,c)))

2020/09/20 23:29

조륜희

public static void main(String[] args) {


            double a, b, c;

            Scanner sc = new Scanner(System.in);
            while(true) {
                System.out.print("a : ");
                a = sc.nextDouble();
                System.out.print("b : ");
                b = sc.nextDouble();
                System.out.print("c : ");
                c = sc.nextDouble();
                sc.nextLine();

                if(a < 0.0000000d || b < 0.0000000d || c < 0.0000000d ||
                        a >= 1000000d || b >= 1000000d || c >= 1000000d)
                    return;

                double s = (a + b + c) / 2;
                double r = Math.sqrt(s * (s - a) * (s - b) * (s - c)) / s;

                System.out.println("The radius of the round table is: " + (Math.round(r * 1000) / 1000d));
        }
    }

2020/09/23 20:26

B A

import math
a,b,c=map(int,input().split())
if not (a and b and c)>1000000 or max(a,b,c)<=((a+b+c)/2):
    s=(a+b+c)/2
    r=(math.sqrt(s*(s-a)*(s-b)*(s-c)))/s
    print(round(r,3))

2020/09/25 10:06

AppleFarmer

import math

# max(a,b,c) <= (a+b+c)/2

'''
삼각형 내접원은 중심으로 나눈 반지름(r)을 높이로 가진 세 삼각형의 합과 삼각형의 넓이가 같다.

삼각형의 넓이 = 1/2(a+b+c)r
'''

# 각 변을 입력 받음
a = float(input())
b = float(input())
c = float(input())

# 헤론의 공식이용 -> area(넓이) 구하기
s = (a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))

# 반지름 = 넓이*2/(a+b+c)
r = round(area/s, 4)
print(r)

2020/09/28 21:02

이셩

import math

class RadiusFinder:
    def __init__(self):
        self.radius = 0
    def guessRad(self,a,b,c):
        s = 0.5*(a+b+c)
        self.radius = math.sqrt((s-a)*(s-b)*(s-c)/s)
        return self.radius

a = 12.0
b = 12.0
c =  8.0

me = RadiusFinder()
b = me.guessRad(a,b,c)

print("The radius of the round table is: {0:10.3f}".format(b))

2020/10/04 16:25

footsize

파이썬입니다. 수식은 인터넷검색을통해 확인했습니다.

def radius():

    a, b, c = "wrong", "wrong", "wrong"
    while not isinstance(a, int) or not isinstance(b, int) or not isinstance(c, int):
        try:
            a = int(input('Please input a length of a side of a triangle a: '))
            b = int(input('Please input a length of a side of a triangle b: '))
            c = int(input('Please input a length of a side of a triangle c: '))

        except:
            continue


    if max(a,b,c) <= (a + b + c)/2:

        s = (a + b + c) / 2
        r = 2*(s*(s-a)*(s-b)*(s-c))**0.5 / (a+b+c)
        print('The radious of the round table is: {0:.3f}'.format(r))

    else:
        print('Invalid lengths of sides')


radius()

2020/10/12 18:30

방금프로그래밍시작함

python 검색해서 헤론의 공식이라는 것을 이용해서 풀어봤습니다. test 파일을 따로 만들어서 사용했는데 아무 숫자나 막 넣다보니, Value Error 혹은 math domain error, 아니면 결과 값이 None 이 되어버리네요. 타당한 3변의 길이를 입력할 식이 필요한 걸까요?

import math, os
def get_radius(point_list):
    if max(point_list[0], point_list[1], point_list[2]) > point_list[0] + point_list[1] + point_list[2]:
        raise Exception()
    else:
        try:
            p = sum(point_list) / 2
            s = math.sqrt(p*((p - point_list[0])*(p - point_list[1])*(p - point_list[2])))
            print("==============================================")
            return round(s/p, 3)
        except ValueError as e1:
            print(e1)
        except Exception as e2:
            print(e2)


def go_testcase():
    path = os.getcwd() + "/test_source_code_file/"
    filename = "006_testcase.txt"
    with open(path+filename, "r") as testcase_file:
        test_cases = testcase_file.readlines()
        for case in test_cases:
            case = case.replace("\n", "")
            test_source = list(map(float, case.split(" ")))
            radius = get_radius(test_source)
            print("The radius of the round table is: {r}" .format(r=radius))

go_testcase()

2020/10/15 23:11

vcne0705

import math

a,b,c = input().split()

a = float(a)
b = float(b)
c = float(c)
s = (a + b + c)/2


area = math.sqrt(s*(s - a)*(s - b) * (s - c))

radi = 2*area / (a+b+c)

print("%.3f"%radi)

2020/11/07 14:34

안상원

a = input("a :")
b = input("b :")
c = input("c :")

s = (int(a) + int(b) + int(c))/2

Area = (s*(s-int(a))*(s-int(b))*(s-int(c))) ** (1/2)

r = 2 * Area / (2*s)

print("Required radius is : %.2f " % r)

2020/11/09 08:49

DSHIN

import math

inp = input("삼각형의 세 변의 길이를 입력하시오:")

i = inp.split(" ")

a = int(i[0])
b = int(i[1])
c = int(i[2])

s = (a+b+c)/2

r=2*math.sqrt(s*(s-a)*(s-b)*(s-c))/(a+b+c)

print("The radius of the round table is: {0}".format(round(r,3)))

2020/11/13 19:48

김우석

from math import sqrt

def Knight_Tale():

a=int(input("first side?"))

b=int(input("second side?"))

c=int(input("third side?"))

total=a+b+c

area=sqrt(total/2*(total/2-a)*(total/2-b)*(total/2-c))

radian=float(area/total*2)

print("The radius of the round table is : {0:.3f}".format(radian))

Knight_Tale()

2020/11/22 22:58

전준혁

while True:
    a,b,c = map(float,input().split())
    if a and b and c:
        s = (a + b + c)/2
        Square = s * (s-a) * (s-b) * (s-c)  
        Square = Square ** 0.5
        r = Square / s
        print("The radius of the round table is : %.3f" %round(r,3))
    else:
        break

2021/01/05 13:04

박성진

import math

a, b, c = input().split()
a = float(a)
b = float(b)
c = float(c)

s = (a + b + c) /2

# (s * r)^2 = s(s-a)(s-b)(s-c)

r = math.sqrt((s-a)*(s-b)*(s-c)/s)

print('The radius of the round table is : ' + '%0.3f' % r)

2021/01/15 16:02

asdfa

def heron(a, b, c):
    if max(a, b, c) > 1000000 or list[2] > list[0]+list[1]:
        print("길이 오류")

    else:
        s = float((a+b+c)/2)
        area = float((s*(s-a)*(s-b)*(s-c))**(1/2))
        r = float(area/s)

        return r


a = float(input("변 길이 입력 : "))
b = float(input("변 길이 입력 : "))
c = float(input("변 길이 입력 : "))

list = [a, b, c]

list = sorted(list)

print(heron(list[0], list[1], list[2]))

2021/01/19 22:53

Jino

[파이썬]

import math
a, b, c = map(float, input("삼각형의 세 변을 입력하시오(띄워쓰기로 구분)\n").split(" "))
# a = 12.0
# b = 12.0
# c = 8.0

s = 0.5*(a+b+c)
# 삼각형 넓이: 내접원 반지름으로 구한 넓이 = 헤론 공식으로 구한 삼각형 넓이
# 1/2 * r(a+b+c) = math.sqrt((s(s-a)(s-b)(s-c)))
r = 2 / (2 * s) * math.sqrt(s*(s-a)*(s-b)*(s-c))

print("The radius of the round table is: %.3f" % r)

2021/02/02 18:31

PenLoo

def main():
    import math
    while 1:
        a = float(input('A : '))
        b = float(input('b : '))
        c = float(input('c : '))
        radius = str(math.sqrt(a**2+b**2+c**2)).split('.')
        R1 = int(radius[0]) # 123
        R2 = int(radius[1][:4]) # 123123213213
        if int(radius[1][3]) >= 5:
            R2 = int(R2/10) + 1
        elif int(radius[1][3]) < 5:
            R2 = int(R2/10)
        radius = R1+R2/1000
        print(radius)


if __name__ == '__main__':
    main()

2021/02/03 09:06

서해원

def triangle(a, b, c):
    import math

    s = (a + b + c) / 2
    area = math.sqrt(s * (s-a) * (s-b) * (s-c))
    r = (2 * area) / (a + b +c)
    r = '{:.3f}'.format(r)

    print('The radius of the round table is:', r)

triangle(12.0, 12.0, 8.0)

2021/02/18 08:22

Ael Lee

import math
a=float(input("삼각형 한변의 첫번째 길이를 입력하세요 : "))
b=float(input("삼각형 한변의 두번째 길이를 입력하세요 : "))
c=float(input("삼각형 한변의 세번째 길이를 입력하세요 : "))
s=float((a+b+c)/2)

A = (s*(s-a)*(s-b)*(s-c))**(1/2)

r = 2*A/(a+b+c)
print("The radius of the round table is : {}".format(round(r,3)))

2021/02/25 21:12

fox.j

def radius(a,b,c):
    import math
    h = math.sqrt(b**2-(c/2)**2)
    r = (c*h)/(a+c+b)
    return print("The Radus of the round table is:",round(r,3))

radius(12,12,8)

2021/06/06 16:33

ss2663

#codingdojing_The Knights Of The Round Table
import math

a, b, c = map(int, input('a b c: ').split())

s = (a+b+c) / 2
S1 = math.sqrt(s*(s-a)*(s-b)*(s-c)) #Heron's Formula
r = S1*2/(a+b+c) #삼각형의 내접하는 원의 반지름 r , S = r(a+b+c)/2

print(f'The radius of the round table is: {r:0.3f}')

2021/08/02 20:44

Jaeman Lee

import math

a,b,c = 12,12,8
s=(a+b+c)/2

r=math.sqrt(((s-a)*(s-b)*(s-c))/s)
print(round(r,3))

2022/02/10 16:08

로만가

from math import *

n= list(map(float,input("삼각형의 세변의 길이를 입력하시오").split(' ')))
a = n[0]
b = n[1]
c = n[2]
s = (a+b+c)/2

r = 2*sqrt(s*(s-a)*(s-b)*(s-c))*(1/(a+b+c))

print('the radius of the round table is:', round(r,3))

삼각형의 세변을 알떄 넓이를 구하는공식과 삼각형의 내접원 성질을 이용해서 구했습니다

2022/02/19 15:29

양캠부부

while True:
    inp = [float(x) for x in input("삼각형의 세 변의 길이를 나타내는 실수 세 개(a,b,c)가 입력: ").split()]
    if len(inp) != 3:
        break
    s = sum(inp)/2
    h = s
    for i in range(3):
        h *= (s-inp[i])

    r = h**0.5/s
    print('The radius of the round table is: {0:.3f}'.format(r))

2023/12/21 13:13

insperChoi

목록으로