공부/Unity 기초
제곱근 판별
svcbn
2022. 5. 12. 19:21
자연수 n에 대해, n이 어떤 자연수 x의 제곱인지 아닌지 판단하려 합니다.
n이 자연수 x의 제곱이라면 x+1의 제곱을,
n이 자연수 x의 제곱이 아니라면 -1을 Console 창에 출력하는 코드를 만들어보세요.
예) n = 9 라면 3의 제곱 입니다. 따라서 (3 + 1) * (3 + 1) = 16이 Console 창에 나오면 됩니다.
n = 5 라면 어떠한 수의 제곱도 아닙니다. 이 경우에는 -1이 Console 창에 나오면 됩니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquareRoot : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
int n = 9;
int answer = 0;
// Math.Sqrt
float f = Mathf.Sqrt(n);
// int 형으로 형변환
int x = (int)f;
// 만약 형변환된 값을 두번 곱한값이 n과 같다면
if (x * x == n)
{
// (x + 1) * (x + 1) 값을 answer에 넣는다.
answer = (x + 1) * (x + 1);
}
// 그렇지 않다면 -1을 answer에 넣는다.
else
{
answer = -1;
}
// 정답을 출력
print(answer);
}
// Update is called once per frame
void Update()
{
}
}