컴퓨터가 1~100 숫자(정수 범위) 중 하나를 랜덤으로 정합니다. (이를 알려주지 않습니다.)
사용자는 이 숫자를 맞추어야 합니다.
입력한 숫자보다 정답이 크면 → "UP" 출력,
입력한 숫자보다 정답이 작으면 → "DOWN" 출력.
정답을 맞추면 → "정답"을 출력하고, 지금까지 숫자를 입력한 횟수를 알려줍니다.
코딩 초보자라도 if 함수와 while함수, 랜덤 모듈 정도까지만 배워도 재미있게 풀 수 있는 문제입니다.
(예시)
컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.
이 숫자를 맞춰주세요.
1~100 숫자 입력:50
DOWN
1~100 숫자 입력:25
UP
1~100 숫자 입력:38
DOWN
1~100 숫자 입력:32
UP
1~100 숫자 입력:35
UP
1~100 숫자 입력:37
DOWN
1~100 숫자 입력:36
정답입니다! 7회 만에 맞췄어요.
100개의 풀이가 있습니다.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN 1 // 정답의 최소값
#define MAX 100 // 정답의 최대값
int main(void)
{
int user_num; // 유저가 입력한 값
int cnt = 1; // 숫자를 입력한 횟수
int crt; // 정답
srand(time(NULL));
crt = (rand() % MAX) + MIN; // MIN~MAX중 랜덤한 숫자 리턴
while(1) {
printf("%d~%d 숫자 입력:", MIN, MAX);
scanf("%d", &user_num);
if(crt == user_num) {
printf("정답입니다! %d회 만에 맞췄어요.\n", cnt);
break;
}
else if(crt < user_num) {
puts("DOWN");
}
else {
puts("UP");
}
cnt++;
}
return 0;
}
import random
A=0
sxice=0
number=int(random.randint(1,100))
print('UP and DOWN 게임 시작!')
while not A==number:
A=int(input())
if A<number:
print('UP')
sxice+=1
elif A>number:
print('DOWN')
sxice+=1
else:
print('정답입니다!!!!!')
print('지금까지 입력한 횟수')
print(sxice+1)
import random
a = random.randint(1,100)
n = 0
print("컴퓨터의 렘덤 숫자를 알아 맞혀보세요.(1~100 사이)") #print("") 수정
q = 0 #추가
while a != q:
q = int(input("1~100 숫자 입력:")) #int( input("") ) 수정
if q < a:
print("up")
elif a < q:
print("down")
n += 1
print("정답입니다.")
print("걸린 순서: "+str(n)) # n -> str(n) 수정
import random
a = random.randint(1,101)
times = 1
while True:
user = int(input("1~100 숫자 입력:"))
if user > a: print("Down") ; times += 1 ; continue
elif user < a: print("Up") ; times += 1 ; continue
elif user == a: break
print("정답입니다!",times,"회 만에 맞췄어요.")
여러번 돌려보면서 재밌었던 문제였네요 ㅎㅎㅎ
import random
print('Up & Down Game!')
x = random.randint(1,100)
l = []
while 1 :
y = int(input('1~100 :'))
if x<y :
print('down')
l.append(y)
continue
elif x>y :
print('up')
l.append(y)
continue
else :
print(f'정답! {len(l)}회!')
break
자바입니다
package may24;
import java.util.Scanner;
public class While03 {
public static void main(String[] args) {
//사용자 입력
Scanner sc = new Scanner(System.in);
//랜덤 두자리
int com = (int) (Math.random() * 99 + 1);
int number = 0;
while (true) {
System.out.println("숫자를 입력해주세요.");
int input = sc.nextInt();
if(com < input) {
System.out.println("Down");
} else if(com > input){
System.out.println("Up");
} else {
System.out.println(number+1 + "번만에 성공하셨습니다.\n축하합니다.");
break;
}
number++;
System.out.println(number + "번째 시도중입니다.");
}
sc.close();
}
}
from random import *
number = randint(1,100)
print(number)
running = True
numbertimes = 0
while running:
numbertimes +=1
question = int(input("1~100 숫자 입력:"))
if number > question:
print("UP")
continue
elif number < question:
print("DOWN")
continue
elif number == question:
print("정답입니다! {0}회 만에 맞췄어요.".format(numbertimes))
running = False
python 3.9.5입니다. 한줄코딩처럼 짧게 하기보다는 가독성에 더 신경을 썼습니다.
import random
print('컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.')
answer = random.randint(1, 100)
times = 0
while True:
times += 1
num = int(input('1~100 숫자 입력:'))
if num < answer: print('UP')
elif num > answer: print('DOWN')
else: break
print(f'정답입니다! {times}회 만에 맞췄어요.')
실행 결과입니다.
컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.
이 숫자를 맞춰주세요.
1~100 숫자 입력:50
DOWN
1~100 숫자 입력:25
DOWN
1~100 숫자 입력:12
UP
1~100 숫자 입력:18
UP
1~100 숫자 입력:21
DOWN
1~100 숫자 입력:19
정답입니다! 6회 만에 맞췄어요.
import random
number = random.randrange(1,101)
print('1~100의 한 숫자를 맞추시오')
tries = 0
while True:
tries += 1
guess = int(input('선택:'))
print('정답' if guess==number else 'UP' if guess>number else 'DOWN')
if guess==number:
print(tries)
break
import random
index = random.randint(1,100)
i = 0
while True :
i = i+1
print("1~100까지 맞추실 숫자를 입력하여 주세요")
ranint = int(input())
if ranint == index: print("정답입니다!{0}회 만에 맞추셨어요!".format(i));break
elif ranint > index: print("DOWN")
elif ranint < index: print("UP")
import random;
randomnumb = random.randint(0, 100) count = 0
while True: pick = int(input('Choose Number 1~100: '))
if pick==randomnumb:
print('Correct')
print('정답입니다!',count,'회 만에 맞췄어요.')
break
elif pick>randomnumb:
print('Down')
count+=1
elif pick<randomnumb:
print('Up')
count+=1
package test02;
import java.util.Scanner;
import java.util.Random;
public class UpAndDown {
public static void main (String[] args) {
int i=0;
int num;
Scanner scan = new Scanner(System.in);
Random random = new Random();
int x = random.nextInt(100);
do {
System.out.println("숫자를 입력하세요 : ");
num = scan.nextInt();
if (x>num) { System.out.println("UP"); }
else if (x<num) { System.out.println("DOWN"); }
i++;
}
while (x!=num);
System.out.println("정답입니다! "+i+"회 만에 맞췄습니다.");
}
}
import random
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.")
print("이 숫자를 맞춰주세요.")
solution = random.randint(1, 100)
pred = 0
count = 0
while solution != pred:
pred = int(input("1~100 숫자 입력: "))
count += 1
if pred < solution:
print("DOWN")
elif pred > solution:
print("UP")
print(f"정답입니다! {count}회 만에 맞췄어요.")
while True: number=input("숫자를 입력하세요:") number2=int(number) if rand>number2: print("UP") elif rand<number2: print("down") else: print("정답") break
import random
value = random.randint(1,100)
running = True
count = 0
while(running):
count += 1
n = int(input("숫자를 맞춰 주세요 : "))
if n == value :
print("축하 합니다. %d번에 맞췄습니다." %count)
running = False
else :
if n < value :
print("Up")
else :
print("Down")
import java.util.Scanner;
public class UpAndDown {
public static void main(String[] args) {
int count = 0;
int randomNum = (int) (Math.random() * 100) + 1;
Scanner sc = new Scanner(System.in);
System.out.println("컴퓨터가 1~100중 랜덤한 숫자를 하나 정했습니다");
System.out.println("이 숫자를 맞춰주세요");
while (true) {
System.out.print("숫자를 입력하세요 >>>");
count++;
int insertNum = sc.nextInt();
if (insertNum > randomNum) {
System.out.println("Down");
} else if (insertNum < randomNum) {
System.out.println("UP");
}
if (insertNum == randomNum) {
System.out.println("정답입니다. 랜덤 숫자는 " + randomNum + "이었습니다. " + count + "회 만에 맞췄어요");
break;
}
}
sc.close();
}
from random import *
r=randint(1,101)
n=0
while (1):
in_num=int(input('1~100 숫자 입력 : '))
n+=1
if r>in_num:
print ('UP')
elif r<in_num:
print ('DOWN')
else:
print ('정답입니다 %d회 만에 맞췄어요' %n)
break
#codingdojing_up_down_game
from random import *
def updown(answer, n):
num = eval(input("Number(1~100): "))
if num == answer:
print(f"Congratulations! You got it right in {n} times")
elif num > answer:
print("Down.")
updown(answer, n+1)
else:
print("Up.")
updown(answer, n+1)
print("""The computer picks a random number(1~100).
Please guess this number.""")
answer = randint(1, 100)
updown(answer, 1)
#end
import random #랜덤 모듈 활성화
number_range = range(1, 101) #숫자 범위 1부터 100까지(정수)
random_number = random.sample(number_range, 1) #1부터 100까지의 숫자중 랜덤으로 한 숫자를 뽑음
random_number = random_number[0] #range 함수가 리스트 자료형이므로 0번째 인덱스로 설정
user_input = 0 #사용자 입력 정의
count = 0 #입력 횟수 정의
try: #예외 구문
while random_number != user_input: #무작위 숫자가 사용자 입력 숫자와 같을 때 까지 반복
user_input = int(input("Enter your guessing number range 1 ~ 100: ")) #사용자 입력 숫자 받음(정수형)
if user_input > 100 or user_input < 1: #사용자 입력 숫자의 범위를 1부터 100까지로 설정
print("Enter number 1 to 100!")
break
elif random_number > user_input: #무작위 숫자가 사용자 입력 숫자보다 클때 "Up"을 출력
count += 1 #입력 횟수 +1
print("Up")
elif random_number < user_input: #무작위 숫자가 사용자 입력 숫자보다 작을때 "Down"을 출력
count += 1
print("Down")
else: #무작위 숫자가 사용자 입력 숫자보다 클때도 작을 떄 도 아닌 같을떄 "Correct"를 출력
count += 1
print("Correct!")
print("Your guess times: "+ str(count)) #입력 횟수를 다 더한 값을 문자열로 변환후 출력
break
except ValueError:
print("Enter valid number!") #사용자가 숫자가 아닌 다른 값을 입력하였을때 예외 처리
import random
i = random.randint(1, 100)
times = 1
while True:
n = int(input("1~100 숫자 입력: "))
if n > i:
print("DOWN")
times += 1
else if n < i:
print("UP")
times += 1
else:
break
print("정답입니다!", times, "회 만에 맞췄어요.")
import random
computer = random.randint(1, 100)
N = 0
count = 0
while computer != int(N):
try:
N = int(input())
if computer > N:
print('UP')
elif computer < N:
print('DOWN')
count += 1
except:
pass
print('정답 횟수 : ', count)
import random
number = random.randrange(1,101)
print('1~100의 한 숫자를 맞추시오')
tries = 0
while tries < 10:
tries += 1
guess = int(input("1~100 숫자 입력: "))
if guess < number:
print("up")
elif guess > number:
print("down")
else:
print("정답입니다. %d회 만에 맞췄어요." % tries)
가독성의 끝판왕을 보여드리겠읍니다
import random
Nunmer = random.randint(1, 101)
Count = 0
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.")
while True:
Answer = int(input("1~100 숫자 입력 : "))
Count += 1
if Answer == Nunmer:
print("정답입니다! {}회 만에 맞췄어요.".format(Count))
break
elif Answer > Nunmer:
print("DOWN")
elif Answer < Nunmer:
print("UP")
package coding_Test.UP_DOWN_Number;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
System.out.println("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다. \n이 숫자를 맞춰주세요.");
int count = 1;
int num = (int) (Math.random() * 100) + 1;
Scanner sc = new Scanner(System.in);
int num_enter = 0;
while (num != num_enter) {
System.out.print("1~100 숫자 입력:");
num_enter = sc.nextInt();
if (num > num_enter) {
System.out.println("UP");
count++;
} else if (num < num_enter) {
System.out.println("DOWN");
count++;
}
}
System.out.println("정답입니다! " + count + "회 만에 맞췄어요.");
sc.close();
}
}
import random
ran=random.randint(1,100)
user=0
time=0
print('컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다. 이 숫자를 맞춰주세요.')
while ran!=user:
user=int(input('1~100 숫자 입력:' ))
time+=1
if ran==user:
print('정답입니다! %d회 만에 맞췄어요.' %(time))
elif ran>user:
print('UP')
else:
print('DOWN')
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
)
func main() {
fmt.Println("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.")
timeSource := rand.NewSource(time.Now().UnixNano())
random := rand.New(timeSource)
randNum := random.Intn(100) + 1
value := 1
count := 0
for {
count++
fmt.Print("1~100 숫자 입력:")
fmt.Scanf("%d", &value)
if value == randNum {
fmt.Println("정답입니다! " + strconv.Itoa(count) + "회 만에 맞췄어요.")
break
} else if value > randNum {
fmt.Println("DOWN")
} else if value < randNum {
fmt.Println("UP")
}
}
}
import random
count = 1
data = random.randint(1,100)
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.")
while True:
N = int(input("1~100 숫자 입력:"))
if (data == N):
break
print("DOWN") if (N > data) else print("UP")
count += 1
print(f"정답입니다! {count}회 만에 맞췄어요.")
C#
using System;
namespace 업앤다운
{
class Program
{
static void Main()
{
var game = new UpAndDownGame();
game.StartGame();
}
}
class UpAndDownGame
{
public UpAndDownGame()
{
Random rand = new Random();
this.Answer = rand.Next(1, 101);
}
private int Answer { get; }
public void StartGame()
{
Console.WriteLine("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.");
int numTry = 0;
while (true)
{
Console.Write("1~100 숫자 입력: ");
string consoleInput = Console.ReadLine();
numTry++;
// Enter, null, whitespace(s)가 입력될 경우 0으로 간주
int guessNumber = string.IsNullOrWhiteSpace(consoleInput) ? 0 : int.Parse(consoleInput);
if (this.Answer == guessNumber)
{
Console.WriteLine($"정답입니다! {numTry}회 만에 맞췄어요.");
break;
}
string message = this.Answer > guessNumber ? "UP" : "DOWN";
Console.WriteLine(message);
}
}
}
}
import random
corNum = random.randrange(1, 101)
inpNo = 0
while True:
inNum = int(input('1~100 숫자(정수 범위)를 입력하세요: '))
inpNo += 1
if inNum < corNum:
print('UP')
elif inNum > corNum:
print('DOWN')
else:
print('정답입니다! {}회 만에 맞췄어요.'.format(inpNo))
break
import random
print('1~100사이의 숫자가 나옵니다\n알아맞춰보세요')
ran = random.randint(1,100)
n = 0
b = 0
while b != ran:
try:
b = int(input('숫자를 입력하세요 : '))
except:
print('"정수"를 입력해 주세요')
continue
if b > ran:
print("DOWN")
elif b < ran:
print("UP")
n += 1
print('정답이에요! ',n,'번만에 맞췄어요!!')
import random
x = random.randint(1,100)
count = 0
while True:
n = int(input(""))
if n > x : print("Down")
elif n < x : print("Up")
count += 1
if n == x : print("정답, %d회" %count)
import random
a = random.randint(1,100)
n = 0
print("컴퓨터의 렘덤 숫자를 알아 맞혀보세요.(1~100 사이)") #print("") 수정
q = 0 #추가
while a != q:
q = int(input("1~100 숫자 입력:")) #int( input("") ) 수정
if q < a:
print("up")
elif a < q:
print("down")
n += 1
print("정답입니다.")
print("걸린 순서: "+str(n)) # n -> str(n) 수정
import random
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다")
print("이 숫자를 맞춰주세요")
num = random.randint(1,100)
innum = input("1~100 숫자 입력 :")
innum = int(innum)
count = 0
while True:
if innum > num:
print("DOWN")
innum = input("1~100 숫자 입력 :")
innum = int(innum)
count += 1
elif innum < num:
print("UP")
innum = input("1~100 숫자 입력 :")
innum = int(innum)
count += 1
else:
print("정답입니다! {}회 만에 맞췄어요.".format(count))
break
import random as rand
isCorrect = 0
count = 0
answer = rand.randint(1,100)
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.")
print("이 숫자를 맞춰주세요.")
while isCorrect == 0:
count += 1
guess = int(input("1~100 숫자 입력: "))
if guess > answer:
print("{} : DOWN".format(guess))
elif guess < answer:
print("{} : UP".format(guess))
elif guess == answer:
print("{} : 정답입니다. {}회 만에 맞췄어요.".format(guess, count))
break
else:
print("입력 숫자를 확인하세요")
``````{.python} import random a=random.randint(1,101) 횟수=1 \n b=1 \n print('1부터 100까지의 숫자중 한개를 컴퓨터가 정합니다 맞춰보세요') \n 대답 = int(input("1~100 숫자 입력:")) \n while b<100: \n if a==대답: \n b=100000000000000000000 \n print('정답입니다 %d 회만에 맞추셧어요 정말 대단해요')%횟수 \n \n\n if a<대답: \n print('up') \n 횟수 +=1 \n \n\n if a>대답:\n print('down') \n 횟수 +=1 \n
```
package org.Coding.dojang;
import java.util.Random;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Random r = new Random();
Scanner sc = new Scanner(System.in);
int up_down = r.nextInt(100)+1;
int count=0;
while(true) {
System.out.print("1~100 숫자 입력 : ");
int human = sc.nextInt();
if(up_down>human) {
System.out.println("UP");
count++;
}
else if(up_down<human) {
System.out.println("DOWN");
count++;
}
else if(up_down==human) {
count++;
System.out.println("GREAT "+count+"회 입력");
break;
}
}
}
}
import random
def updowncheck(random_num, write_num):
if random_num > write_num:
return True
elif random_num < write_num:
return False
def equalcheck(random_num, write_num):
if random_num == write_num:
return True
else:
return False
def main():
random_num = random.randint(1, 100)
count = 0
while True:
count += 1
write_num = int(input("숫자를 입력하여 주세요 : "))
if equalcheck(random_num, write_num):
print(f"{count}번 만에 맞추셨습니다!")
break
up = updowncheck(random_num, write_num)
if up == True:
print("Up")
elif up == False:
print("Down")
print("")
if __name__ == "__main__":
main()
import random
def find_the_number():
cnt = 0
while True:
i = int(input("(1~100) 숫자를 입력하시요: "))
cnt += 1
if a > i:
print("UP")
elif a < i:
print("DOWN")
else:
print("정답입니다! {0}번 만에 맞췄어요.".format(cnt))
break
if __name__ == '__main__':
a = random.randint(1,100)
find_the_number()
import random
ans = random.randint(1,100)
count=0
print('컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.')
while True:
user_input=(input('1~100 숫자 입력 : '))
count += 1
if ans > int(user_input):
print('UP')
elif ans < int(user_input):
print('DOWN')
else:
print('정답입니다.! %d회 만에 맞췄어요.'%count)
break
http://coding1up1down.creatorlink.net/render/INTRO
사이트에 코드 있습니다.(크리에이트 링크로 만듬 https://creatorlink.net)
파이썬입니다
from random import randrange
def main():
print("1에서 100사이의 숫자를 맞춰보세요.")
r = randrange(100) + 1
i = 0
while True:
n = int(input("1~100: "))
i += 1
if n == r:
print("정답!")
break
print("UP" if r > n else "DOWN")
print(f"{i}번만에 맞췄어요!")
if __name__ == '__main__':
main()
import random
com = random.randint(1,100)
cnt = 0
print('컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.')
mynum = int(input('1~100 숫자 입력 '))
while True:
if com==mynum:
print('정답입니다! {}회 만에 맞췄어요.'.format(cnt))
break
elif mynum > com:
print('DOWN')
mynum = int(input('1~100 숫자 입력 '))
else:
print('UP')
mynum = int(input('1~100 숫자 입력 '))
cnt+=1
from random import *
right = randrange(1, 101)
num = "Unknown"
count = 0
print(right)
while num!= str(right):
print("이 숫자를 맞춰주세요.")
num= input("1~100 숫자 입력 : ")
if right <= int(num):
print("Down")
count += 1
else:
print("Up")
count += 1
print("정답입니다! {0}회만에 맞추셨어요.".format(count))
static int num = (int) (Math.random() * 100) + 1;
static int count = 0;
static boolean onOff = true;
static String upDown(int x) {
++count;
if (x == num) {
onOff = false;
return "정답입니다. " + count + "회 만에 맞췄어요.";
} else if (x > num) {
return "Down";
} else {
return "Up";
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("1 ~ 100사이 숫자를 입력하세요.");
while (onOff) {
System.out.println((upDown(s.nextInt())));
}
}
자바로 만든 소스코드입니다.
package updown;
import java.util.*;
public class updown {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
int random = (int) (Math.random()*100)+1; //1~100까지 랜덤으로 출력하는 함·난수
System.out.println("★ 업 앤 다운 게임 ★");
while(true) { //동일한 숫자 나올때까지 {} 있는 내용 반복
System.out.print("숫자를 입력해주세요 : ");
int num = sc.nextInt();
count++;
if(random < num) {
System.out.println("down");
}
else if(random > num) {
System.out.println("up");
}
else if(random == num) { //정답일 경우 while문에서 break;를 주어 빠져나온다
System.out.println("정답입니다. " + count + " 회 만에 맞추셨습니다.");
break;
}
}
sc.close();
}
}
import random
num=random.randint(1,101)
print("컴퓨터가 1~100중 랜덤한 숫자를 고릅니다.")
user=0
time=0
while user != num :
print("1~100 숫자 입력:")
user=int(input())
if user>num:
print("DOWN")
time += 1
continue
elif user<num:
print("UP")
time += 1
continue
elif user == num :
print("정답")
time +=1
break
print("입력하신 횟수는", time, "번 입니다.")
import random
e=0
a=random.randint(1,101)
b=0
while b=1
c=int(input('숫자를 입력하시오'))
e=e+1
if a==c:
b=1
print('%d회만에 맞추셧습니다.'%e)
Python입니다
import random
goal = random.randint(1, 101)
print("please guess the random number")
tried = 0
user = 50
while goal != user:
user = int(input())
if goal > user:
tried += 1
print("Up!")
elif goal < user:
tried += 1
print("Down!")
elif goal == user:
print("Correct!")
print("You got it within "+ str(tried) + " of tries")
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요")
import random
y = random.randint(1,100)
i = 1
while i:
x = int(input("1~100 숫자 입력:"))
if x > y:
print("DOWN")
elif x < y:
print("UP")
else:
print("정답입니다! %d회 만에 맞췄어요." % i)
break
i += 1
var comAnswer = Math.floor(Math.random() * 100) + 1;
var count = 1;
var userAnswer = -1;
while(userAnswer != comAnswer) {
var input = prompt('컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다. 이 숫자를 맞춰주세요.');
userAnswer = parseInt(input);
if(userAnswer < comAnswer) {
alert("UP");
} else if(userAnswer > comAnswer) {
alert("DOWN");
} else {
alert("정답입니다! " + count + "회 만에 맞췄어요.");
break;
}
count ++;
}
from random import *
correct = randrange(1,101)
n = 1
while correct != predict:
predict = int(input('숫자를 입력하세요'))
if correct > predict:
print('업')
n += 1
elif correct < predict:
print('다운')
n += 1
print(f'정답입니다 {n}회만에 맞추셨습니다. ')
from random import*
a = randint(1,51)
Goal = 0
count = 0
while a != Goal:
count += 1
Goal = int(input("숫자를 입력 : "))
if Goal > a:
print("Up!")
elif Goal < a:
print("Down!")
elif Goal == a:
break
print("정답입니다.")
print(f"도전 횟수는 {count} 회 입니다.")
import random
num = random.randint(1,100)
n =0
while True :
n +=1
while True :
a = int(input())
if a>=1 :
break
if a > num :
print("Down")
elif a < num :
print("Up")
else :
print("정답입니다!",n,"회 만에 맞췄어요")
break
import random
num = random.randint(1,101)
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요")
count = 0
while True:
ans = int(input("1~100 숫자 입력: "))
if ans < num:
print("UP")
count = count + 1
elif ans > num:
print("DOWN")
count = count + 1
elif ans == num:
print("정답입니다! " + str(count) + "회 만에 맞췄어요.")
import random
hidden = random.randint(0,100)
n=0
while suggest != hidden:
suggest = int(input('어떤 숫자일까요?'))
n= n+1
if suggest > hidden:
print('이야기 하신 숫자는 답안보다 큰 숫자에요.. 작은 숫자를 말해 주세요.')
else:
print('이야기 하신 숫자는 답안보다 직은 숫자에요.. 큰 숫자를 말해 주세요.')
print(f' 정답은 {hidden}입니다. {n}번에 맞추셨어요..')
import random
com_num = random.randint(1,100)
c = True
count = 1
while c:
num = int(input(">>>"))
if num > com_num:
print("down")
count+=1
elif num < com_num:
print("up")
count+=1
else:
print(str(com_num)+"end")
print(count)
c = False
간단하게 만들었습니다
import random
import time
a = random.randint(1,100)
n=1
b = random.randint(1,100)
b_up = 100
b_down = 1
if b==a:
print(f'{n}번의 시도로 완성했읍니다. 정답은 {a}입니다.')
else:
while b!=a:
n=n+1
if b < a:
print(f'n:{n},a:{a},b:{b} up')
time.sleep(5)
b_down = b
b = random.randint(b_down+1,b_up-1)
elif b>a:
print(f'n:{n},a:{a},b:{b} down')
time.sleep(5)
b_up = b
b = random.randint(b_down+1,b_up-1)
print(f'{n}번의 시도로 완성했읍니다.정답은 {a}입니다.')
import java.util.Random;
import java.util.Scanner;
public class RandomNumGame {
public static void main(String[] args) {
Random random = new Random();
int answer = random.nextInt(100);
System.out.println(("정답 미리보기: ") + answer);
int input_number;
int repeat_count = 0;
Scanner scan = new Scanner(System.in);
System.out.println("1~100사이의 숫자중 랜덤 숫자를 맞추시오.");
do {
System.out.print("정답: ");
input_number = scan.nextInt();
repeat_count++;
if (input_number > answer) {
System.out.println("더 작은 수를 입력하세요.");
}
if (input_number < answer) {
System.out.println("더 큰 수를 입력하세요.");
}
} while (input_number != answer);
System.out.printf("정답입니다. 총 시도횟수는 %d회 입니다.\n", repeat_count);
}
}
// Rust
// rand crate 이용하였습니다.
use rand::Rng; fn guessing_game() {
let num = rand::thread_rng().gen_range(1..101);
let mut count = 0;
loop {
println!("1~100 숫자 입력:");
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("input error");
let input: usize = input.trim().parse().unwrap();
count += 1;
if input < num {println!("UP");}
else if input > num {println!("DOWN");}
else {break;}
}
println!("{}회 만에 정답!", count);
}
package org.javaturotials.ex;
import java.util.*;
import java.util.stream.Collectors;
public class test {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int rd = (int)(Math.random()*100 + 1);
int count=0;
while(true) {
int num =sc.nextInt();
if(num<rd) {
System.out.println("UP");
}
else if(num>rd) {
System.out.println("DOWN");
}
else {count++;
break;}
count++;
}
System.out.println("정답입니다. " +count + "회 만에 맞췄습니다." );
}
}
package section01;
import java.util.Scanner;
public class MathCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("1~100 사이에 숫자를 맞춰보세요 : ");
int num = sc.nextInt();
int randomNum = (int)(Math.random() * 100 + 1);
int i = 1;
while(true) {
if(num > randomNum) {
System.out.println("DOWN");
i++;
} else if(num < randomNum) {
System.out.println("UP");
i++;
} else if(num == randomNum) {
System.out.println("정답입니다." + i + "회 만에 맞췄어요.");
break;
}
System.out.println("1~100 사이에 숫자를 맞춰보세요 : ");
num = sc.nextInt();
};
}
}
import random
a=random.randint(1,100)
i=1
while 1:
n= int(input("숫자를 입력하세요!: "))
if a==n:
print("정답! %d회 만에 맞췄어요!" %i)
break
else:
if a>n:
print("UP")
i=i+1
elif a<n:
print("DOWN")
i=i+1
import random
def updown_game():
answer = random.randint(1, 100)
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.")
print("이 숫자를 맞춰주세요.")
count = 0
while True:
count += 1
inNum = int(input("1~100 숫자 입력"))
if inNum < answer:
print("UP")
elif inNum > answer:
print("DOWN")
else:
print(f"정답입니다! {count}회 만에 맞췄어요.")
break
updown_game()
import random
def UPDown(n):
count = 0
com = n
user = int(input("1~100 숫자 입력:"))
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.")
print("이 숫자를 맞춰주세요.")
while True:
if com > user:
print("UP")
count += 1
user = int(input("1~100 숫자 입력:"))
elif com == user:
return "정답입니다! %d회 만에 맞췄어요."%count
else:
print("DOWN")
count += 1
user = int(input("1~100 숫자 입력:"))
print(UPDown(random.randint(1, 100)))
import random
number = random.randrange(1,101)
count = 0
while True:
a = int(input("1부터 100까지의 랜덤한 숫자를 맞춰주세요 : "))
if a > number:
print("Down")
count += 1
elif a < number:
print("UP")
count += 1
elif a == number :
count += 1
print("랜덤 숫자 {}를 {}회 만에 맞추셨습니다 !".format(number,count))
break
import java.util.Scanner;
public class CodingStamp_03 {
public static void main(String[] args) {
int correctAnswer = (int)(Math.random()*100 + 1); //컴퓨터가 1~100 숫자(정수 범위) 중 하나를 랜덤으로 정함
int input = 0; //사용자의 입력
int count = 0; //시도 횟수를 기록
Scanner scanner = new Scanner(System.in);
System.out.println("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.");
System.out.println("이 숫자를 맞춰주세요.");
while (input != correctAnswer) {
System.out.println("1~100 숫자 입력: ");
input = scanner.nextInt();
count++;
if (input > correctAnswer) {
System.out.println("DOWN");
} else if (input < correctAnswer) {
System.out.println("UP");
} else {
System.out.println("정답입니다. " + count + "회 만에 맞췄어요.");
break;
}
}
}
}
자바로 풀어봤습니다.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
int answer = (int)(Math.random()*100);
Scanner scan = new Scanner(System.in);
int tryData, count=0;
System.out.println("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.");
while(true) {
System.out.println("1~100 숫자 입력:");
tryData = scan.nextInt();
count++;
if(tryData>answer) {
System.out.println("Down");
}else if(tryData<answer) {
System.out.println("Up");
}else {
break;
}
}
System.out.printf("정답입니다! %d회 만에 맞췄어요.\n", count);
}
}
파이썬(22/06/21)
import random
num = random.randint(1,100)
number = 0
count = 0
while num != number:
number = int(input("1~100 숫자입력: "))
if num > number:
print("UP")
count = count + 1
if num < number:
print("DOWN")
count = count + 1
print("정답입니다. %d회 만에 맞췄어요." % count)
java(23/04/01)
import java.util.Random;
import java.util.*;
public class up_down_game
{
public static void main(String[] args)
{
Random random = new Random();
int random_num = 0; //컴퓨터가 생성하는 랜덤값(정답)
int num = 0; // user가 입력한 값
int count = 1; // 입력횟수
random_num = random.nextInt(99)+1; //1~100
Scanner scanner = new Scanner(System.in);
for (;;)
{
System.out.printf("1~100중 숫자 하나를 입력해주세요");
num = scanner.nextInt();
if (num == random_num)
{
System.out.printf("정답!!!%n");
System.out.printf("횟수: %d", count);
break;
}
if (num > random_num)
{
System.out.printf("Down%n");
count += 1;
}
if (num < random_num)
{
System.out.printf("Up%n");
count += 1;
}
}
}
}
C++(26/06/23)
#include <iostream>
#include <random>
using namespace std;
int main() {
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int> distribution(0, 100);
int randomNum = distribution(gen);
cout << "UP and DOWN 숫자맞추기 게임입니다." << endl;
cout << "컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다." << endl;
cout << "이 숫자를 맞춰주세요." << endl;
int count = 1;
while (true) {
int num = 0;
cout << "1~100 숫자 입력:";
cin >> num;
if (randomNum == num) {
cout << count << "회 만에 맞췄어요" << endl;
break;
}
else if (randomNum > num) {
cout << "UP" << endl;
count++;
}
else {
cout << "DOWN" << endl;
count++;
}
}
}
import random
random = random.randint(1, 100)
num = 0
count = 0
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다. \n이 숫자를 맞춰주세요.")
while num != random:
count += 1
num = input("1~100 숫자 입력: ")
num = int(num)
if num > random:
print("DOWN")
else:
print("UP")
print("정답입니다! %d회 만에 맞췄어요." % count)
import random as r
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞혀주세요.")
cr = r.randint(1, 100)
c = 0
while True:
ui = int(input("1~100 숫자 입력: "))
if ui > cr:
c += 1
print("DOWN")
elif ui < cr:
c += 1
print("UP")
elif ui == cr:
c += 1
print("정답입니다! %d회 만에 맞혔어요." % c)
break
재미있네요
파이썬 3.10
import random
rand_num = random.randrange(1, 100)
# print(rand_num)
count = 0
input_num = 0
while rand_num != input_num:
input_num = input("guess a number : ")
count += 1
if input_num == "":
print("Inpur Number")
elif rand_num > int(input_num):
print("Up")
elif rand_num < int(input_num):
print("Down")
elif rand_num == int(input_num):
print("Correct")
print("input count is ", count)
break
많은 분들과 비슷하게 작성 된것 같고요. 아무것도 입력되지 않았을때 오류가 나지않고 다시 한번 입력해 달라고 하는 메시지 띄우는 구문을 추가 해보았습니다.
import random
comnum = random.randint(1, 101)
count = 0
while True:
mynum = int(input("enter a number:"))
count += 1
if mynum > comnum:
print("down")
elif mynum < comnum:
print("up")
else:
print("correct!", "you've got the answer in", count, 'times.')
break
import java.util.Random; // 임의의 수를 지정하기 위한 임포트
import java.util.Scanner; // 플레이어의 숫자 입력을 받기 위한 임포트
public class UpNDown { // 클래스명은 게임 이름으로
public static void main(String[] args) { // 메인메소드
Random r = new Random(); // 랜덤메소드 객체 선언
Scanner sc = new Scanner(System.in); // 스캐너메소드 객체 선언
int rNum = r.nextInt(1, 100); // 랜덤숫자 변수 선언하며 범위 설정 (1~100) 및 변수 초기화
int playerNum = 0; // 플레이어가 입력할 숫자 변수 선언 및 초기화
int times = 0; // 실행된 횟수를 담을 변수 선언 및 초기화
try { // 잘못된 입력을 걸러내기 위한 명령어
while (true) { // 얼마나 많이 입력할지 모르기 때문에 아래에서 break;문으로 탈출
times++; // 실행된 횟수 증감식
System.out.print("\n1~100 숫자 입력:"); // 안내메시지출력
playerNum = Integer.parseInt(sc.next());// 플레이어입력 변수에 입력된 숫자 대입(이하 플레이어 숫자)
if (rNum == playerNum) { // 만약 랜덤숫자와 플레이어가 입력한 숫자가 같다면
System.out.printf("정답입니다! %d회 만에 맞혔습니다.", times); // 실행된 횟수 출력
break; // while문 탈출
} else if (rNum > playerNum) { // 랜덤 숫자가 플레이어 숫자보다 크다면
System.out.println("UP"); // UP 출력
} else if (rNum < playerNum) { // 랜덤 숫자가 플레이어 숫자보다 작다면
System.out.println("DOWN"); // DOWN 출력
} // if~else문 종료
} // while문 종료
} catch (Exception e) { // 잘못된 입력을 하여 오류를 낸 경우
System.err.println("잘못된 입력입니다. 프로그램을 종료합니다."); // 오류 메시지 출력
}
} // 메인메서드 종료
}
자바로 작성하였습니다.
package UpDown;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
int com = (int) (Math.random() * 100 + 1);
Scanner sc = new Scanner(System.in);
int count = 0;
int num = 0;
while (num != com) {
System.out.println(count + "번째 시도");
System.out.println("입력해주세요");
System.out.println("============");
num = sc.nextInt();
if (num < com) {
System.out.println("입력숫자가 더 작습니다.");
} else if (num > com) {
System.out.println("입력숫자가 더 큽니다.");
}
count = count + 1;
if (num == com) {
break;
}
}
System.out.println("정답숫자는" + com + "입니다.");
System.out.println(count + "번만에 맞추셨습니다.");
}
}
public class Up_Down {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("숫자를 입력하시오");
int cnt = 0;
int com = (int) (Math.random() * 100) + 1;
while (true) {
int tmp = sc.nextInt();
cnt++;
if (tmp > com) {
System.out.println("UP");
} else if (tmp < com) {
System.out.println("DOWN");
} else {
System.out.printf("정답! 입력한 횟수는 : %d", cnt);
break;
}
}
}
}
import random
print('컴퓨터가 1~100 숫자(정수 범위) 중 하나를 랜덤으로 정합니다. \n이 숫자를 맞춰주세요.')
num = random.randint(1,100)
answer = False
count = 0
while answer == False :
user = int(input('1~100 숫자 입력 : '))
count = count + 1
if num == user :
print(f'정답입니다! {count}회 만에 맞췄어요.')
answer = True
elif user > num : print('DOWN')
elif user < num : print('UP')
import random
q = random.randint(1, 100)
count = 1
while True:
a = int(input(print("1~100 숫자 입력 : ")))
if (a < q):
print("UP")
count += 1
elif (a > q):
print("DOWN")
count += 1
else:
print("정답입니다! %d회만에 맞혔어요." % count)
break
# Codingdojang 266
import random
a=random.randint(1,101)
i=0
while i==0:
temp=input("예상 값을 입력하세요.(1~100):")
temp=int(temp)
if temp<a:
print("Up")
elif temp>a:
print("Down")
elif temp==a:
print("True")
i=1
print("답:%d"%temp)
import random
def main():
random_num = random.randint(1, 100)
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.")
guess = int(input("1~100 숫자 입력: "))
guess_count = 0
while guess != random_num:
if guess > random_num:
print("DOWN")
guess_count += 1
else:
print("UP")
guess_count += 1
guess = int(input("1~100 숫자 입력: "))
print("정답입니다!", str(guess_count), "회 만에 맞췄어요.")
if __name__ == '__main__':
main()
import random
print('''컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.
이 숫자를 맞춰주세요.''')
answer = random.randint(1,100)
count = 0
while True:
count += 1
num = int(input("1~100 숫자 입력:"))
if answer > num:
print("UP")
elif answer < num:
print("DOWN")
else:
print(f"정답입니다! {count}회 만에 맞췄어요.")
break
Python 결과물이 재미있는 프로그래밍은 만들면서도 재미있네요. 좋은 문제 감사합니다.
import random
r_answer = random.randint(1, 100)
count=0
while True:
count+=1
answer = int(input('정답(1~100 사이의 수)을 입력해 주세요. : '))
if answer > r_answer:
print('Down!')
elif answer < r_answer:
print('Up!')
elif answer == r_answer:
print('Correct!')
print('총 %d번 만에 정답을 맞췄습니다.' %count)
break
import random
setnb = random.randint(1,100); cnt = 0
print("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n이 숫자를 맞춰주세요.")
while True:
number = int(input("1~100 숫자 입력: "))
cnt += 1
if number == setnb:
print("정답입니다! "+str(cnt)+"회 만에 맞췄어요.")
break
elif number>setnb: print("DOWN")
else: print("UP")
from random import *
nums = randint(1,100)
user_input = int(input("1~100사이 숫자를 입력 : "))
count = 0
while nums != user_input :
if nums > user_input :
print("UP")
user_input = int(input("1~100사이 숫자를 입력 : "))
count += 1
else :
print("DOWN")
user_input = int(input("1~100사이 숫자를 입력 : "))
count += 1
else :
print(f"정답은 {nums}입니다. \n{count + 1}번 만에 맞췄습니다.")
Python
import random
n = random.randint(1, 100)
count = 1
print(n)
while True:
put = int(input('1~100 숫자 입력'))
if put == n:
break
else:
if put > n:
print('DOWN')
else:
print('UP')
count += 1
print('정답입니다! {}회 만에 맞췄어요.'.format(count))
import random
answer=random.randint(1,100)
count = 0
a = int(input("1~100 사이의 숫자를 입력하세요."))
count = count + 1
while True:
if answer == a:
print("정답입니다. 총 %s번만에 맞추셨어요" %count)
break
elif answer > a:
print("UP")
a = int(input("1~100 사이의 숫자를 입력하세요."))
count = count + 1
if answer < a:
print("DOWN")
a = int(input("1~100 사이의 숫자를 입력하세요."))
count = count + 1
import random
ran_num = random.randrange(1, 101)
count = 0
while(1):
while(1):
input_num = input("숫자 입력(1~100)")
try:
input_num = int(input_num)
break
except:
print('잘못된 입력입니다. 재입력 하세요')
count += 1
if ran_num == input_num:
print("정답")
print("횟수 : {}".format(count))
break
elif ran_num > input_num:
print("Up")
else: #ran_num < input_num:
print("Down")
import random
ans = random.randint(1, 100)
cnt, estimate = 0, 0
print('\n\n컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.')
print('이 숫자를 맞춰주세요.')
while ans != estimate:
estimate = int(input('1~100 숫자 입력: '))
if estimate < ans:
print('UP')
elif estimate > ans:
print('DOWN')
cnt += 1
print("정답입니다! {0}회 만에 맞췄어요.".format(cnt))
import random
times = 1
num = random.randrange(1,101)
while True:
times += 1
user = int(input("Enter Number:"))
if user > num:
print("DOWN",user)
elif user < num:
print("UP",user)
elif user == unm:
print("You Right !!!")
break
print("You succeeded in",times,"tries")
import random
answer = random.randrange(1,100)
count = 0 while True:
# 숫자 입력받기
input_num = input ("숫자를 입력하세요:")
number = int(input_num)
count += 1
if number == answer:
print ("정답입니다")
print ("{}번만에 맞추셨습니다.".format(count))
break
if number > answer:
print ("Go Down")
elif number < answer:
print ("Go Up")
from random import randint
n = randint(1, 100)
m = 0
cnt = 0
while True:
m = int(input())
if m == n:
print(f"Got it. You've tried {cnt} times.")
break
elif m > n:
print("Too high")
else:
print("Too low")
cnt += 1
namespace MyFirstProject
{
internal class Program
{
static void Main(string[] args)
{
var game = new UPandDownGame();
game.StartGame();
}
}
class UPandDownGame
{
private static int NUMTRY_MAX = 7; // 시도 기회 수
private int Answer { get; } // 정답값 넣는 변수
private static Random random = new Random(); // 랜덤함수
int numTry = 0;// 시도 횟수
public UPandDownGame()
{
this.Answer = random.Next(1, 999); //랜덤 값을 Answer에 집어넣기
}
public void StartGame()
{
Console.WriteLine("컴퓨터가 1~999 중 핸덤 숫자 하나를 정합니다. \n이 숫자를 맞춰주세요.");
while (true) //true를 넣으면 계속 while 문 실행
{
Console.Write("1~999 숫자 입력 : ");
string consoleInput = Console.ReadLine(); // consoleInput 변수에 입력값 넣기
numTry++;
//만약 어느 하나의 조건도 만족하지 않는다면, 즉 변환에 실패하거나 범위를 벗어나는 입력값이라면 if문 안에 작업이 수행됩니다:
if (!int.TryParse(consoleInput, out int guessNumber) || guessNumber < 1 || guessNumber > 999)
{
Console.WriteLine("숫자 1~999를 입력해주세요.");
numTry --;
continue; //현재 반복을 종료하고 다음 반복을 시작합니다
}
if (this.Answer == guessNumber)
{
Console.WriteLine($"정답입니다! {numTry}회 만에 맞췄어요.");
break;
}
string message = this.Answer > guessNumber ? "UP" : "DOWN";
Console.WriteLine(message);
if (numTry < NUMTRY_MAX)
{
Console.WriteLine($"{NUMTRY_MAX - numTry}회 남으셨습니다.");
}
else
{
Console.WriteLine("횟수를 초과 하셨습니다.");
break;
}
}
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
srand(time(NULL));
int rand_num = 1 + rand() % 100;
int n;
int cnt = 0;
printf("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.\n");
printf("이 숫자를 맞춰주세요.\n");
while(1){
printf("1~100 숫자 입력 : ");
scanf("%d", &n);
cnt += 1;
if(n > rand_num){
printf("UP\n");
}else if(n < rand_num){
printf("DOWN\n");
}else{
printf("정답입니다! %d회 만에 맞췄어요.\n", cnt);
break;
}
}
return 0;
}
import random
num = random.randint(1,100)
your_num = 0
while num != your_num:
your_num = int(input('숫자 :'))
if your_num > num:
print('down')
elif your_num < num:
print('up')
print('정답!')
package test;
import java.util.Random;
import java.util.Scanner;
public class month5_8_1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Random rd = new Random();
int random = rd.nextInt(100)+1;
int cnt = 1;
System.out.println("컴퓨터가 1~100 중 랜덤 숫자 하나를 정합니다.");
System.out.println("이 숫자를 맞춰주세요.");
System.out.print("1~100 숫자 입력 : ");
int a = sc.nextInt();
while(random != a) {
if(a < random) {
System.out.println(a + "보다 더 큽니다.");
} else {
System.out.println(a + "보다 더 작습니다.");
}
System.out.print("다시 입력해주세요 : ");
cnt += 1;
a = sc.nextInt();
}
System.out.println("정답입니다! " + cnt + "회 만에 맞췄어요.");
}
}
import random
A=0
B=0
number=int(random.randint(1,100))
while True:
print("컴퓨터가 1~100 중 랜덤 숫자를 하나를 정합니다. \n 이 숫자를 맞춰주세요.")
A = int(input("1~100 숫자 입력: "))
B += 1
if A > number:
print("DOWN")
elif A < number:
print("UP")
elif A == number:
print("정답입니다 %s회 만에 맞췄어요" % B)
break
import random
print("컴퓨터가 1~100중 숫자 하나를 랜덤으로 정합니다")
print("이 숫자를 맞춰 주세요")
num = random.randrange(1, 101)
# print(num)
inValue = 0
n = 0
while num != inValue:
n += 1
inValue = int(input("1~100중에서 숫자를 입력해 주세요: "))
if num > inValue:
print("UP")
elif num < inValue:
print("DOWN")
print("정답입니다." + str(n) + "번 만에 맞추셨습니다")
print("정답은" + str(inValue) + "입니다")
import random
def numCheck(a):
b = int(input("1-100 숫자 입력: "))
if b > a: print("DOWN"); return True
elif b < a: print("UP"); return True
else: return False
a = random.randint(1,100)
chk = True
cnt = 0
while chk == True:
chk = numCheck(a)
cnt += 1
print(f"정답입니다! {cnt}회 만에 맞췄어요")
import random
trial = 0
x = random.randrange(1,101) #랜덤으로 1부터 100까지의 정수 하나 추출
print("""컴퓨터가 1~100 중 랜덤 정수 하나를 정합니다.
이 숫자를 맞춰주세요.""") #시작 멘트
while True:
answer = int(input("1~100 숫자 입력: "))
if answer < x:
print("Up")
trial+=1
elif answer > x:
print("Down")
trial+=1
else:
trial+=1
break
print("정답입니다! %d회 만에 맞췄습니다."%trial)
import promptSync from 'prompt-sync';
const prompt = promptSync();
function upAndDown() {
const answer = Math.floor(Math.random() * 100) + 1;
let count = 0;
while (true) {
const guess = Number(prompt(`(${count + 1}번째) 숫자를 입력하세요: `))
count++
if (guess > answer) {
console.log('DOWN');
} else if (guess < answer) {
console.log('UP');
} else {
console.log(`정답: ${count}번 만에 맞췄습니다.!`);
break;
}
}
}
upAndDown();