초기 투자액과 투자 기간, 그리고 투자 기간 중 날짜별 가치 변동율이 주어질 때 순이익과 이익 여부를 구합니다.
첫째 줄에 투자액이 정수로 주어집니다. 두번째 줄에 투자기간이 정수로 주어집니다. 세번째 줄에 투자기간 중 일별 전일 대비 가치 변동이 각각 퍼센트 단위의 정수로 주어집니다.
첫째 줄에 순이익을 소수점 첫째자리에서 반올림한 값으로 나타냅니다. 두번째 줄에 이익인지 손해인지 여부를 good, same, bad로 나타냅니다. 이익이면 good, 손해이면 bad, 첫째줄에서 출력한 순이익이 0이면 same울 출력합니다.
10000
4
10 -10 5 -5
-125
bad
70개의 풀이가 있습니다.
public void calc()
{
double changed = money;
int profit;
for(int i=0; i<days; i++)
{
changed = changed + (changed * fluctuation[i] * 0.01);
}
profit = (int) Math.round((changed - money));
System.out.println("순수익 : " + profit);
if(profit >= -0.5 && profit <= 0.5)
System.out.println("Same");
else if(profit > 0.5)
System.out.println("Good");
else
System.out.println("Bad");
}
C로 풀었습니다. 다른 부분은 쉬웠는데 소수점 반올림 부분에서 고민했네요..
int money, day, i;
double profit=0, changed_money=0;
int arr[10];
while(1){
printf("투자액 입력");
scanf_s("%d", &money);
if(money < 100 || money >10000){
fprintf(stderr, "투자액 에러\n");
continue;
}
printf("투자 일 수 입력");
scanf_s("%d", &day);
if(day <=0 || day > 10){
fprintf(stderr, "투자 일 수 에러\n");
continue;
}
printf("일별 변동폭 데이터를 투자 일 수만큼 입력(변동폭은 음수도 가능)\n");
for(i=0; i<day; i++)
scanf_s("%d", &arr[i]);
changed_money=money;
for(i=0; i<day; i++)
changed_money=changed_money + (changed_money * arr[i] * 0.01);
profit= (changed_money - money);
if(profit >= 1){
printf("\n순수익\n");
printf("%d\n", (int)(profit+0.5));
printf("Good\n");
break;
}else if(-1 < profit && profit <1){
printf("\n순수익\n");
if(profit < 0){
profit= -profit;
profit= profit+0.5;
profit= -profit;
printf("%d\n", (int)profit);
}
printf("%d\n", (int)(profit+0.5));
printf("Same\n");
break;
}else{
printf("\n순수익\n");
if(profit < -1){
profit= -profit;
profit= profit+0.5;
profit= -profit;
}
printf("%d\n", (int)profit);
printf("Bad\n");
break;
}
}
import random
import time
def stock(money,day):
print(f'{money}원 투자!\n')
for d in range(1,day):
GodHand = random.randint(-100,100)
print(f'{d}일, 날이 밝았습니다.','#'*10)
if GodHand < 0 :
money += GodHand
print(f'{money}!\n아 .. 지금이라도 팔아야하나..?\n')
elif GodHand > 0 :
money += GodHand
print(f'{money}!\n존버는 승리한다.\n')
else : print(f'{money}!\n 오늘은 평화롭군\n')
time.sleep(2)
stock(10000,10)
너무 쉬워요.
inv_amt = input("Invest Amount? ")
inv_day = input("Days? ")
inv_profit = input("Profit rates? ").split(" ")
#print(inv_profit)
def real_profit(a, d, p):
sum_profit = a
for i in range(d):
profit = sum_profit * int(p[i]) / 100
sum_profit += profit
print("%d day: %d" %(i,sum_profit))
return sum_profit
profit = real_profit(inv_amt, inv_day, inv_profit)
print("Total: %d" %profit)
if profit > 0:
print("Good!!!")
elif profit == 0:
print("So so...")
elif profit < 0:
print("Bad!!!")
#include <iostream>
#include <cmath>
#define D(x) x > 0 ? cout << "good" << endl : cout << "bad" << endl
using namespace std;
inline double cal(double x,double y);
inline double halfup(double z);
int main()
{
int b=0,i;
double a,temp;
do {
cout << "투자액 입력(100 <= a <= 10,000) : ";
cin >> a;
} while (a > 10000 || a < 100);
temp = a;
do {
cout << "투자 일 수 입력(1 <= b <= 10) : ";
cin >> b;
} while (b > 10 || b < 1);
double dnum[b];
for (int i=0;i<b;(dnum[i] >= -100 && dnum[i] <= 100) ? i++ : i){
cout << i+1 << "번째 입력: ";
cin >> dnum[i];
}
for (int j=0;j<b;j++)
a = cal(a,dnum[j]);
double pf = halfup((a - temp));
cout << "순 이익 : " << pf << endl;
((a - temp) > -0.5 && (a - temp < 0.5)) ? cout << "same" << endl : D(pf);
}
inline double cal(double x,double y)
{
double num;
y >= 0 ? num = (x + (x * (y / 100))) : num = (x + (x * (y / 100)));
return num;
}
inline double halfup(double z)
{
z = z - 0.5;
return ceil(z);
}
# 파이썬
money=int(input("Invest money?:"))
day=int(input("Invest day?:"))
result=[]
for i in range(day):
r=float(input("Please write %d day rates?:" %(i+1)))
result.append(r)
def stock(a,d,p):
first_money=a
for i in range(d):
m=first_money*int(p[i])/100
first_money +=m
print("%d day: %d" %(i+1,first_money))
return first_money
print("")
print("-------Profit money--------")
t=stock(money,day,result)
print("Total: %d" %t)
a=t-money
if a>0:
print("Good!!")
elif a==0:
print("So so...")
elif a<0:
print("Bad!!")
#include <stdio.h>
int main(){
double a,j,c;
int b,i;
scanf("%lf%d",&a,&b);
j=a;
for(i=0;i<b;i++)
{
scanf("%lf",&c);
a*=(c/100+1);
}
printf("%.0f\n",a-j);
if(a-j<0) printf("bad");
if(a-j==0) printf("same");
if(a-j>0) printf("good");
}
public class Stock {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int money = Integer.parseInt(sc.nextLine());
double d = money + 0d;
int days = Integer.parseInt(sc.nextLine());
for(int i = 0; i < days; i++) {
d *= ((100 + sc.nextInt()) / 100d);
}
int delta = (int)d - money;
System.out.println(delta);
if(delta < 0) {
System.out.println("bad");
} else if(delta > 0){
System.out.println("good");
} else {
System.out.println("same");
}
sc.close();
}
}
c입니다
#include <stdio.h>
double fluctuation(double money, double range)
{
double final = money + (money * range / 100);
return final;
}
int main(void)
{
double a = 0, b = 0, aa = 0;
int i = 0;
int range[10];
scanf_s("%lf", &a);
while (!(100 <= a <= 10000))
scanf_s("%lf", &a);
aa = a;
scanf_s("%lf", &b);
while (!(1 <= b <= 10))
scanf_s("%lf", &b);
for (i = 0; i < b; i++)
{
scanf_s("%d", &range[i]);
aa = fluctuation(aa, range[i]);
}
printf("%.0f\n", aa-a);
if ((aa-a)==0)
printf("same");
else if ((aa-a) < 0)
printf("bad");
else
printf("good");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int invsize;
printf("Please insert how much you would like to invest.\n: ");
scanf("%d", &invsize);
if (invsize < 100 || invsize > 10000)
{
printf("That is not proper size to initiate your investment on stock.\n You had better to abandon it.");
}
int howlong;
printf("Please insert how long you would like to invest.\n: ");
scanf("%d", &howlong);
if (howlong < 1 || howlong > 10)
{
printf("That is not proper period to initiate your investment on stock.\n You had better to abandon it.");
}
int fluct[howlong];
float multiple[howlong];
int cnt;
for(cnt = 0; cnt < howlong; cnt++)
{
printf("Please insert the fluctuation ratio of the day %d in terms of percent.\n: ", cnt+1);
scanf("%d", &fluct[cnt]);
if (fluct[cnt] < -100 || fluct[cnt] > 100)
{
printf("That is not proper daily fluctuation ratio. Get Lost.");
exit(1);
}
fluct[cnt] = fluct[cnt] + 100;
multiple[cnt] = fluct[cnt] * 0.01;
}
float finmult = 1.0000;
int cnt2;
for (cnt2 = 0; cnt2 < howlong; cnt2++)
{
finmult = finmult * multiple[cnt2];
}
printf("\n\nThe result is: %.1f \n", (invsize*finmult - invsize));
if((invsize*finmult - invsize) > -0.5 && (invsize*finmult - invsize) < 0.5)
{
printf("\nThe final Evaluation: Same!");
}
else if((invsize*finmult - invsize) >= 0.5)
{
printf("\nThe final Evaluation: Good!");
}
else
{
printf("\nThe final Evaluation: Bad!");
}
return 0;
}
C로 작성하였습니다. 굳이 구조화하지는 않았습니다.
stock.text 내용은 위에 인풋 내용 그대로입니다.
10000 4 10 -10 5 -5
f1 = open("stock,text")
a = int(f1.readline()
b = f1.readline()
s = f1.readline()
an = a
for c in s.split() :
an = int ( an + an * int(c) / 100 )
print an -a
print ( ( an-a > 0.5 ) and "good" or ( (an-a < -0.5) and "bad" or "same" ) )
파이썬 3.5
money_init = 10000 #초기 투자금
profit = [10, -10, 5, -5] #4일간 수익률
def calc(money_init, profit):
result = money_init
for i in profit:
result += result * i * 0.01
print(result)
if result > money_init:
print('good')
elif result == money_init:
print('same')
else:
print('bad')
calc(money_init, profit)
a = input("input the initial amount of money:")
b = input("input the duration of your investment, in days:")
c = raw_input("input the fluctuation of each day, in percentages, divided by spaces:")
lst = []
sublst=[]
intlst=[]
for i in range(len(c)):
sublst.append(c[i])
if c[i] == " ":
sublst.remove(" ")
lst.append(sublst)
sublst = []
elif i == len(c) -1 :
lst.append(sublst)
sublst = []
for i in range(len(lst)):
intlst.append(eval("".join(lst[i])))
result = float(a)
for i in intlst:
result = result * ((i+100)/100.0)
print round(result, 0) - a
if result > a:
print "good"
elif result == a:
print "same"
else:
print "bad"
init=input()
num=input()
changes = map(int,raw_input().split())
final = reduce(lambda i,c : 1.0*i*(100+c)/100, [init]+changes)
result = int(final - init)
print result
print ['bad','same','good'][result/abs(result)+1]
#coding: CP949
a=float(input('투자액(100~10,000):'))
b=int(input('투자일 수(1~10):'))
c=[]
while len(c)<b:
c.append(int(input('%d번째 날의 주식 변동율을 입력하시오(-100~+100):'% (len(c)+1))))
a_result=a
for i in c:
a_result+=a_result*(0.01*i)
print('%0.0f' % (a_result-a))
if a_result-a>0:
print('good')
elif a_result==a:
print('same')
else:
print('bad')
파이썬 3.4 동적입력값
어리둥절...
from functools import reduce
def main():
a = int(input())
b = int(input())
c = [int(x) for x in input().split()[:b]]
d = [1.0 + x / 100 for x in c]
r = reduce(lambda x,y: x*y, d, a) - a
print("{:.0f}".format(r))
print("good" if r > 0 else ("same" if r == 0 else "bad"))
main()
Ruby
profit = -> { prn, _, *per = $stdin.read.split.map &:to_i
per.reduce(prn) {|bal,p| bal*(p*0.01+1)} - prn }
stat = ->s=profit[].round { puts s, %w(same good bad)[s<=>0] }
Test
$stdin = StringIO.new("10000\n4\n10 -10 5 -5\n")
expect { stat.call }.to output("-125\nbad\n").to_stdout
Python 3.4.4
a = 10000
b = 4
point = [10, -10, 5, -5]
result = a
for x in point:
result += result * x // 100
output = result - a
print(output)
if output > 0.5:
print("good")
elif output < -0.5:
print("bad")
else:
print("same")
C#으로 작성했습니다.
using System;
using System.Collections.Generic;
public static class Question083FindNetProfit
{
public static void Answer()
{
var inputs = new List<int> {10, -10, 5, -5};
var output = FindNetProfit(10000, inputs);
}
public static int FindNetProfit(int income, List<int> inputs)
{
var price = (decimal) income;
foreach (var input in inputs)
price += price * input / 100;
return (int) Math.Floor(price - income);
}
}
a=int(input('투자액? '))
money=copy.copy(a)
b=int(input('투자일수?'))
for k in range(b):
s=float(input('%d일의 변동 ___ %%' %(k+1)))
if not -100<=s<=100:
print('-100에서 +100까지만요')
break
money*=(1+s/100)
profit=money-a
print('수익 : %1.0f' %profit)
if profit>=0.5:
print('good')
elif profit<=0.5:
print('bad')
else:
print('same')
def do(a, b):
c = a
for x in b:
c += (c * x / 100)
c = c - a
print(round(c))
if c >= 0.5:
print('good')
elif c > -0.5:
print('same')
else:
print('bad')
do(10000, [10, -10, 5, -5])
Python 3.5.2 에서 작성하였습니다.
base = int(input())
day = int(input())
X = base
for x in [int(a) for a in input().split(' ')]:
X += X / 100 * x
result = round(X - base)
if X - base >= 0.5:
print(result,'Good',sep='\n')
elif X - base <= -0.5:
print(result,'bad',sep='\n')
else:
print(result,'same',sep='\n')
#### 2017.01.16 D-401 ####
def stock(data):
S, n, dS=data
S_new=S
for i in range(n):
S_new=S_new*(1+dS[i]/100)
S_new=round(S_new)
if (S_new)==S:
result=[S_new-S,"same"]
elif (S_new)<S:
result=[S_new-S,"bad"]
else:
result=[S_new-S,"good"]
print("%d\n%s" %(result[0],result[1]))
stock([10000,4,[10,-10,5,-5]])
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class InvestmentInStocks {
public static void main(String[] args) throws FileNotFoundException {
String path = InvestmentInStocks.class.getResource("").getPath();
Scanner sc = new Scanner(new File(path + "InvestmentInStocks.txt"));
Double amount = sc.nextDouble();
Integer days = sc.nextInt();
Double result = amount;
for (int i = 0; i < days; i++) {
result = result + (result * sc.nextInt() / 100);
}
System.out.println(Math.round(amount - result));
System.out.println(amount < result ? "good" : "bad");
}
}
python 3.6 변동폭은 하나님만이 아시는 것이기 때문에 random 모듈을 사용해서 생성하게 했습니다. (미리 알 수 있다면 때부자)
import random
seed = int(input("How much is your seed money? "))
period = int(input("How long is your investment period? "))
fluctuation = [random.randint(-100,100) for i in range(period)]
print(fluctuation)
def closing(inv,fluc):
for r in fluc:
inv *= 1 + r/100
return inv
net_gain = int(round((closing(seed,fluctuation) - seed),0))
if net_gain > 0:
print("%d\ngood" % net_gain)
elif net_gain < 0:
print("%d\nbad" % net_gain)
else:
print("%d\nsame" % net_gain)
// 주식 투자 - C#
using System;
namespace GetRich
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Ready>>>");
int money = 0, time = 0;
do
{
money = int.Parse(Console.ReadLine());
} while (money < 100 || money > 10000);
do
{
time = int.Parse(Console.ReadLine());
} while (time < 1 || time > 10);
int[] percent = new int[time];
REJECT:
string a = Console.ReadLine();
for (int i = 0; i < time; i++)
{
percent[i] = int.Parse(a.Split(' ')[i]);
if (percent[i] > 100 || percent[i] < -100)
goto REJECT;
}
double result = money; double plus = money;
for (int i = 0; i < time; i++)
plus += (plus / 100 * percent[i]);
result -= plus; result = Math.Round(result);
Console.WriteLine(result);
if (result < 0)
Console.WriteLine("bad");
else if (result == 0)
Console.WriteLine("same");
else
Console.WriteLine("good");
}
}
}
investment = int(input("투자액 : "))
dates = int(input("투자 일수 : "))
profit = []
for i in range(1, dates + 1) :
s = int(input(("%s번째 수익률 : ") % (i)))
profit.append((s + 100) * 0.01)
result = investment
for a in profit :
result = result * a
print("순수익 : %s" % (round(result - investment)))
if result >= investment * 1.005 :
print("투자 성공")
elif investment * 1.005 > result > investment * 0.995 :
print("도긴개긴")
else :
print("투자 좆망")
def cal(start, prof):
tmp=list(prof)
def inner(s, t):
tmpp=s*(1+t.pop(0)/100)
if not t: return(tmpp)
else: return(inner(tmpp, t))
result=round(inner(start,tmp)-start)
if result>0: msg='good'
elif result<0: msg='bad'
else: msg='same'
return(str(result)+'\n'+msg)
a=int(input())
b=int(input())
while True:
per=list(map(int, input().split()))
if len(per)==b: break
print(cal(a, per))
a=input('투자액?')
b=input('투자일수?')
c=input('변동폭?')
a=int(a)
a1=int(a)
b=int(b)
c=c.split()
for i in range(b):
a=a+(a*int(c[i])/100)
result=round(a-a1)
if abs(result)<0.5:result=0
if result>0:
print(result)
print('good')
if result==0:
print(result)
print('same')
if result<0:
print(result)
print('bad')
파이썬 3.6
def inputdata():
t = 0
a = int(input("투자액 = "))
if 100 <= a <= 10000:
data.append(a)
else:
print("범위내의 값을 입력하세요")
return
b = int(input("투자 일 수 = "))
if 1 <= b <= 10:
data.append(b)
else:
print("범위내의 값을 입력하세요")
return
for i in range(data[1]):
t = int(input("%d일차 변동폭 :"%(int(i)+1)))
if -100 <= t <= 100:
data.append(t)
else:
print("범위내의 값을 입력하세요")
return
def benefitcheck(data):
benefit = data[0]
for i in range(data[1]): benefit += benefit*(int(data[i+2])/100)
result = round(benefit-(int(data[0])))
print(result)
if data[0] < result: print("good")
elif data[0] == result: print("same")
else: print("bad")
if __name__ == "__main__":
data = []
result = 0
inputdata()
print("\n")
try:
benefitcheck(data)
except IndexError:
print("프로세스를 종료합니다.")
투자액 = 10000
투자 일 수 = 4
1일차 변동폭 :10
2일차 변동폭 :-10
3일차 변동폭 :5
4일차 변동폭 :-5
-125
bad
# 파이썬
def stock(l1):
r = l1[0]
for m in l1[2]: r = r * (100+m) / 100
r = round(r - l1[0])
print(r)
if r > 0: print('good')
elif r < 0: print('bad')
else: print('same')
input_sample = [10000, 4, [10, -10, 5, -5]]
stock(input_sample)
def stock(a, c):
b = a
for i in c:
b = b * (100+int(i))/100
if abs(b-a) < 0.5:
return b-a, "same"
elif b-a > 0:
return b-a, "good"
else:
return b-a, "bad"
a = int(input())
c = input().split(' ')
print(stock(a, c))
investment_amount=int(input("투자액을 입력하세요:"))
if 100>investment_amount or investment_amount>10000:
invest_money=int(input("다시 입력하세요:"))
invest_period=int(input('투자기간을 입력하세요:'))
if 1>invest_period or 10<invest_period:
invest_period(int(input("다시 입력하세요:")))
stock_volatility_list=input("변동폭을 입력하세요:").split(' ')
if len(stock_volatility_list)!=invest_period:
stock_volatility_list=input("다시 입력하세요:").split(' ')
Total_revenue=investment_amount
for num in stock_volatility_list:
Total_revenue*=(100+int(num))/100
Net_income=round(Total_revenue-investment_amount)
if Net_income==0:
print('0')
print('same')
elif 0.5<Net_income:
print("%d"%Net_income)
print('good')
elif -0.5>Net_income:
print("%d"%Net_income)
print('bad')
import java.util.Scanner;
public class inCome{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("투자액을 입력하시오 (100 <= 투자액 <= 10,000)");
int a = sc.nextInt();
float result1 = a;
System.out.println("투자일 수를 입력하시오 (1 <= 투자일 수 <= 10)");
int b = sc.nextInt();
int [] c = new int [b];
System.out.println("일별 변동폭인 데이터를 투자일 수만큼 입력하시오 (-100 ~ +100)");
for(int i=0;i<b;i++){
c[i] = sc.nextInt();
}
for(int j=0;j<b;j++){
result1 *= ((float)c[j]/100) + 1.0;
}
int income = Math.round(result1-a);
System.out.println("\n" + income);
if(income<0)
System.out.println("bad");
else if(income>0)
System.out.println("good");
else
System.out.println("same");
}
}
def stock():
invest = int(input("insert the investment : (100 <= amount <= 1000) : "))
seed = invest
days = input("insert the day : (1 <= amount <= 10) : ")
flow = input("insert the flow : (-100 <= amount <= 100) : ")
flowlist= flow.split(' ')
for i in map(int,flowlist):
invest = invest * ((100 + i)/100)
print(round(invest - seed))
if round(invest - seed) > 0 : print("good")
elif round(invest - seed) == 0 : print("same")
elif round(invest - seed) < 0 : print("bad")
print(stock())
Python
a = 10000 #a = int(input())
b = 4 #b = int(input())
data = [10, -10, 5, -5] #data = list(map(int, input().split(' ')))
final = a
for i in range(b):
final += final*data[i]*0.01
print(final)
final -= a
print("{:.0f}".format(final))
if final > 0:
print("good")
elif final < 0:
print("bad")
else:
print("same")
inAmount = 0.00
opDays = 0
earningsRatioList = ""
ratio = 0.00
inAmount = float(input("투자액 입력: "))
originAmount = inAmount
opDays = input("투자일수 입력: ")
earningsRatioList = input("수익율 입력")
for word in earningsRatioList.split(" "):
ratio = float(int(word))
inAmount = inAmount * (1.0 +(ratio * 0.01))
print(int(inAmount))
netIncome = inAmount - originAmount
if 0.5 > netIncome > -0.5:
answer = "same"
elif netIncome <= -0.5:
answer = "bad"
elif netIncome >= 0.5:
answer = "good"
print(answer)
#첫번째줄에 투자액 a가 입력됩니다. (100 <= a <= 10,000)
a = int(input("투자액 a: "))
a1 = a
if not (a>=100 and 10000>=a):
print("투자액 데이터를 잘못 입력")
exit()
# 둘번째줄에 투자 일 수 b가 입력됩니다.(1 <= b <= 10)
b = int(input("투자일 수 b: "))
if not (10>=b and b>=1):
print("투자일 수 데이터를 잘못 입력")
exit()
#세번째줄에 일별 변동폭인 데이터가 날짜 갯수(b개)만큼 퍼센트 정수로 입력됩니다. (변동폭는 음수도 될 수 있습니다.) ( 범위 -100 ~ +100)
c = map(int, input("변동폭%").split())
for _c in c:
if not (100>=_c and _c>=-100):
print("변동폭 데이터를 잘못 입력")
exit()
#수익 및 손실 연산
for i in range(b):
a = a + (a * c[i] / 100)
# 이 사람의 순수익(=총 수익(최종 값) - 총 비용(투자한 액수))을 소수점 첫째 자리에서 반올림하여 첫째 줄에 출력한다.
# 만약 0.5>순수익>-0.5이면 순수익은 0으로 봅니다.
benefit = round(a - a1)
print(benefit)
# 그리고 다음 줄에 이 사람이 이득일 경우 "good", 본전일 경우 "same", 손해일 경우 "bad"를 출력하세요.
if benefit > 0:
print("good")
elif benefit == 0:
print("same")
else:
print("bad")
money = int(input())
day = int(input())
percent = map(int,input().split())
tmp = money
for i in percent: tmp *= (100+i)/100
result = round(tmp - money)
print(result,'good' if result>0 else 'bad' if result<0 else 'same',sep='\n')
파이썬에서 round(0.5) = round(-0.5) = 0 이네요.
검색해도 뚜렷한 해결책이 안 보여서
0.49999.... 를 살짝 키워서 0.5 이상으로 만드는 꼼수를 썼습니다.
input_str = '10000\n4\n10 -10 5 -5'
invest = int(input_str.split('\n')[0])
daily_ratio = map(int, input_str.split('\n')[2].split())
ratio = 1
for r in daily_ratio:
ratio *= 1 + r / 100
profit = round(invest * (ratio * 1.00001 - 1))
print(profit)
if profit > 0: print('good')
elif profit < 0: print('bad')
else: print('same')
import java.util.Scanner;
import java.util.Random;
public class KimSanghyeop
{
public static void main(String[] args)
{
Scanner sc =new Scanner(System.in);
System.out.print("투자금 입력 : ");
int money = sc.nextInt();
System.out.print("투자기간 : ");
int day = sc.nextInt();
// 일별 전일 대비 가치 변동은 랜덤으로
Random rd = new Random();
int change;
double res=money;
int f1;
for(f1=0;f1<day;f1++)
{
change = rd.nextInt(200) -100;
res = res + res * change/100;
System.out.println((f1+1)+" days 이율 : "+change);
}
System.out.println("change : "+(int)(res-money));
}
}
def stock(am,*var):
co = am
for x in var:
co += co*x/100
print('%d\n%s' %(round(co-am,0),'BAD'if co-am < 0 else 'GOOD' if co-am > 0 else 'SAME'))
C#
using System;
using System.Linq;
namespace CD083
{
class Program
{
static void Main()
{
int investValue = int.Parse(Console.ReadLine());
int duration = int.Parse(Console.ReadLine());
int[] valueChangeInPercent = new int[duration];
valueChangeInPercent = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
Console.WriteLine(GetNetProfit(investValue, valueChangeInPercent));
}
static string GetNetProfit(int investValue, int[] valueChangeInPercent)
{
double balance = investValue;
foreach (var change in valueChangeInPercent)
{
balance = balance * (1 + (double)change / 100);
}
double returnValue = Math.Round(balance - investValue);
string EstimateString = returnValue > 0 ? "good" : "bad";
if (returnValue == 0) { EstimateString = "same"; }
return returnValue.ToString() + Environment.NewLine + EstimateString;
}
}
}
money = int(input())
day = int(input())
profit = input().split(' ')
temp_money=money
for i in range(day):
temp_money *= (int(profit[i])/100+1)
temp_money = round(temp_money)
if money > temp_money: print("%s\n%s"%(temp_money-money, 'bad'))
elif money < temp_money: print("%s\n%s"%(temp_money-money, 'good'))
else: print("%s\n%s"%(0, 'same'))
money = int(input())
period = int(input())
change = list(map(int, input().split()))
if len(change) > period:
raise Exception('range is too much')
def investment(money, change):
seed = money
for i in change:
money *= (1 + (i/100))
net = money - seed
if net > 0:
return round(net), '\ngood'
elif money == seed:
return round(net), '\nsame'
else:
return round(net), '\nbad'
print(*investment(money,change))
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int money = Integer.parseInt(sc.nextLine());
int period = Integer.parseInt(sc.nextLine());
String profit = sc.nextLine();
getProfit(money, period, profit);
sc.close();
}
public static void getProfit(int money, int period, String profit) {
String[] strArr = profit.split(" ");
int[] intArr = new int[period];
for (int i = 0; i < period; i++) {
intArr[i] = Integer.parseInt(strArr[i]);
}
double result = money;
double per;
for (int i = 0; i < period; i++) {
per = intArr[i];
per /= 100;
per += 1;
result *= per;
}
result -= money;
System.out.println(Math.round(result));
if (result < 0) System.out.println("Bad");
else if (result > 0) System.out.println("Good");
else System.out.println("Same");
}
미천한 코드입니다 ㅋㅋ
money0=int(input());kikan=int(input());hendoL=list(map(int,input().split()));money=money0
for i in hendoL:
money*=(1+i/100)
jud = round(money-money0);print(jud)
if jud>0:
print('good')
elif jud==0:
print('same')
else:
print('bad')
import java.util.*;
public class 주식투자 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double money = scan.nextInt();
int days = scan.nextInt();
double[] gain = new double[days];
for(int i=0; i<days; i++) {
gain[i] = scan.nextInt();
}
double profit = 0;
double money2 = money;
for(int i=0; i<days; i++) {
money2 = money2+(money2*(gain[i]/100));
}
profit = money2 - money;
if(profit>0) {
System.out.println(Math.round(profit));
System.out.println("good");
}
else if(profit==0) {
System.out.println(Math.round(profit));
System.out.println("same");
}
else {
System.out.println(Math.round(profit));
System.out.println("bad");
}
}
}
python 3
def 투자평가(초기금액, 투자일, 변동율):
최종금액 = 초기금액
for r in 변동율:
최종금액 += 최종금액 * r*0.01
순이익 = round(최종금액) - 초기금액
if 순이익 > 0:
평가 = 'good'
elif 순이익 < 0:
평가 = 'bad'
else:
평가 = 'same'
print('순이익:', 순이익)
print('평가:', 평가)
초기금액 = int(input('투자금액: '))
투자일 = int(input('투자일: '))
변동율_ = input('변동율: ')
변동율 = [int(i) for i in 변동율_.split(' ')]
투자평가(초기금액, 투자일, 변동율)
init_value = int(input("초기 투자 금액 : "))
term = int(input("투자기간(1~10) : "))
value = 0
term_value =[]
cal_sum = 0
if term < 11 and term > 0 :
for i in range(term):
value = int(input())
if value <= 100 and value >= -100:
term_value.append(value)
else :
print("재입력(-100~100)")
break
cal_sum = init_value
for j in term_value:
cal_sum = cal_sum * j/100 + cal_sum
print("수익 :" , round(cal_sum-init_value))
if cal_sum-init_value > 0:
print("good")
elif cal_sum-init_value < 0:
print("bad")
else :
print("same")
else :
print("재입력(1~10)")
import random
inv=int(input("100~10000 사이의 투자액을 입력하십시오: "))
oinv=inv
prd=int(input("1~10 사이의 투자 기간을 입력하십시오: "))
for n in range(prd):
r=random.randint(-100,100)/100
inv=inv+(inv*r)
profit=inv-oinv
print(round(profit))
if profit>0:
print("Good")
elif profit==0:
print("Same")
else:
print("Bad")
문제를 잘못읽어서 날짜별 변동폭을 입력으로 받는게 아니고 랜덤으로 뽑게했습니다.
def stock(i, p, c):
f = i
for k in c:
i += i * (k / 100)
r = i - f
return round(r, 0), 'bad' if r < 0 else ('same' if r == 0 else 'good')
def main():
i = 10000
p = 4
c = 10, -10, 5, -5
b, r = stock(i, p, c)
print(b, r, sep= '\n')
if __name__ == '__main__':
main()
money = int(input())
long = input()
change = str(input()).split()
m = [money,]
for i in change:
money += round((money)*(int(i)/100))
m.append(money)
if m[-1]-m[0] < 0:
print(m[-1]-m[0],"bad")
elif m[-1]-m[0] ==0:
print(m[-1]-m[0],'same')
else:
print(m[-1]-m[0],'good')
파이썬3입니다.
import random as r
initialCapital = r.randint(100,10000)
duration = r.randint(1,10)
changeRate = [(100+r.randint(-100,100))*0.01 for _ in range(duration)]
resultCaptital = initialCapital
for x in range(duration) :
resultCaptital *= changeRate[x]
print(f'Initial captital is {initialCapital}. Result captital is {resultCaptital}.')
if initialCapital>resultCaptital :
print('BAD')
elif initialCapital<resultCaptital :
print('GOOD')
else:
print('SAME')
m=int(input("투자액은 100이상 10000 이하의 정수입니다 : "))
d=int(input("투자기간은 1이상 10 이하의 정수입니다. : "))
h=list(map(int,input("일별 변동폭은 -100이상 100이하의 정수입니다 : ").split()))
def money(m,d,h) :
M=int(m)
for i in range(1, d+1) :
M+=M*((h[i-1])/100)
soon=round(M-m)
print(soon)
if soon > 0 :
print ("good")
elif soon < 0 :
print("bad")
else :
print ("same")
money(m,d,h)
inv_amt = input("Invest Amount? ") inv_day = input("Days? ") inv_profit = input("Profit rates? ").split(" ")
def real_profit(a, d, p): sum_profit = a for i in range(d): profit = sum_profit * int(p[i]) / 100 sum_profit += profit print("%d day: %d" %(i,sum_profit)) return sum_profit
profit = real_profit(inv_amt, inv_day, inv_profit) print("Total: %d" %profit) if profit > 0: print("Good!!!") elif profit == 0: print("So so...") elif profit < 0: print("Bad!!!")
cash = int(input())
period = int(input())
variable = input()
value = float(cash)
V = variable.split(" ")
for i in range(period) :
value = value * ((100 + int(V[i]))/100)
profit = round(value - cash)
print(profit)
if profit > 0 :
print('good')
elif profit < 0 :
print('bad')
else :
print('same')
def stock():
seed=int(input("write seed money : "))
period=int(input("write year you invest :"))
change=input('change :')
changes=change.split(' ')
for i in range(0,len(changes),1):
changes[i]=(int(changes[i])+100)/100
answer=1
for j in changes:
answer=answer*j
answer=seed-int(seed*(answer))
print(answer)
if 0>answer:
print("bad")
elif seed==answer:
print("same")
else:
print("good")
stock()
def invest(money, day, change):
money_init = money
_change = list(change.split(' '))
for i in range(day):
money += money*(int(_change[i])/100)
profit = round(money - money_init)
if profit > 0:
message = 'GOOD'
elif profit == 0:
message = 'SAME'
else:
message = 'BAD'
print(money, day, profit, message)
invest(10000,4,'10 -10 5 -5')
def Stock(a):
if 100<=a<=10000:
b=int(input("투자기간을 입력하세요 :"))
if 1<=b<=10:
d=a
i=0
while i<b:
c=int(input("변동폭 입력 :"))
if -100<=c<=100:
a*=(1+float(c/100))
i+=1
else:
print("변동폭 오류")
return False
print(int(a)-d)
if int(a)-d>0:
print("good")
elif int(a)-d==0:
print("same")
else:
print("bad")
else:
print("투자기간을 다시설정하세요")
else:
print("투자액을 다시 설정하세요")
Stock(int(input("투자액을 입력하세요 : ")))
def fund(info):
info = info.split("\n")
third_info = info[2].split(" ")
info.pop(-1)
info.append(third_info)
money = int(info[0])
change = info[2]
final = 0
for i in change:
final += money / 100 * int(i)
result = money - final
if result > 0:
return "good", round(result)
elif result < 0:
return "bad", round(result)
else:
return "same", round(result)
original = 10000
invest = 10000
term = 4
percent = '10 -10 5 -5'.split(' ')
#Result
#1. 순이익을 소수점 첫째자리에서 반올림한 값
#2. 이익인지, 손해인지를 good/same/bad로 나타냄
for i in percent:
invest *= (1 + int(i)/100)
net = invest - original
print(round(net))
if net > 0 : print('good')
elif net == 0 : print('same')
elif net < 0 : print('bad')
#codingdojing_stock investment
import sys
amount = eval(input('investment amount: '))
term = eval(input('period of investment: '))
fluctation = input('fluctation: ')
i_amount = amount
l_fluctation = list(map(int, fluctation.split()))
if term != len(l_fluctation):
print('input error')
sys.exit()
for i in l_fluctation:
i_amount += i_amount*i/100
result = i_amount - amount
print(round(result))
if result < 0: print('bad')
elif result == 0: print('same')
else: print('good')
def stock_investment(a,f,c):
b = a
for i in c:
b += b * i//100
if b-a > 0.5:
return b-a, "good"
elif b-a < -0.5:
return b-a, "bad"
else:
return b-a,"same"
if __name__ == '__main__':
a = 10000
f = 4
c = [10,-10,5,-5]
print(stock_investment(a,f,c))
daily_fluc =[]
while True:
cash = int(input("초기 투자금?"))
if cash>=100 and cash <=10000:
break
while True:
period = int(input("투자 기간?"))
if period >=1 and period <=10:
break
daily_fluc =[]
current_money = cash
for k in range(period):
while True:
print(k+1,"번째날의 ",end="")
fluct = int(input("변동폭을 입력하시오"))
if fluct >=-100 and fluct <=100:
daily_fluc.append(fluct)
break
for i in daily_fluc:
current_money *=(100+i)/100
difference = current_money - cash
if difference>0 :
print(round(difference))
print("good")
elif difference<0 :
print(round(difference))
print("bad")
else:
print("0")
print("same")
_input1 = int(input())
_input2 = int(input())
_input3 = list(map(int,input().split()))
answer = _input1
for i in range(0,_input2):
answer += answer * (_input3[i]/100)
answer = int(round(answer - _input1,0))
print(answer)
if answer > 0 : print("good")
elif answer== 0 : print("same")
else : print("bad")
a = 10000
change = '10 -10 5 -5'
change.split(' ')
change_result = 1
for i in change.split(' '): change_result *= (100+int(i))/100
profit = a*(change_result-1)
print(round(profit))
if profit > 0:
print('good')
elif profit == 0:
print('same')
else:
print('bad')
M = int(input("투자금액: "))
D = int(input("투자기간: "))
UD = [int(x) for x in input("가치변동: ").split()]
m = M
for i in UD:
m += m *i/100
print(round(m-M))
if m-M > 0: print('good')
elif m-M < 0: print('bad')
else: print('same')
money = int(input("투자액 입력(100이상 10000이하의 정수) : "))
day = int(input("투자기간 입력(1이상 10이하의 정수) : "))
var = [] # 변동폭 리스트
profit = money # 이익
print("일별 변동폭 입력(-100이상 100이하의 정수) : ")
for i in range(day):
var.append(int(input()))
for i in range(day):
profit *= (0.01*(100 + var[i]))
pure = profit - money # 순이익
print("순이익 : %.0lf" %(pure))
if (pure == 0):
print("평가 : %s" %("same"))
elif (pure > 0):
print("평가 : %s" %("good"))
if (pure < 0):
print("평가 : %s" %("bad"))
파이썬입니다.
invest_amount = int(input("투자액? "))
invest_period = int(input("투자기간? "))
change_value = [int(i) for i in input("일별 전일 대비 가치 변동? ").split()]
def cal_profit(m, d, lst):
for r in lst:
m = int(m * (1 + r/100))
return m
profit = cal_profit(invest_amount, invest_period, change_value) - invest_amount
print(profit)
if profit > 0:
print('good')
elif profit < 0:
print("bad")
else:
print('same')