2017-03-23 7 views
0

私は更新されたコードでこの質問を再掲載しています。変数カウンタをゼロから始めるように設定しますが、

長年にわたって得られた単純な関心を計算するためにこのコードを実行すると(素晴らしい表形式で)、私のテーブルの列は5で始まります。また、合計は5から始まる年で計算されます。明確にするために、私はtotYearを求められたときにユーザー入力の例として5を使用しています。

#Declare the necessary variables. 
princ = 0 
interest = 0.0 
totYear = 0 
year = 1 

#Get the amont of principal invested. 
print("Enter the principal amount.") 
princ = int(input()) 

#Get the interest rate being applied. 
print("Enter the interest rate.") 
interest = float(input()) 

#Get the total amount of years principal is invested. 
print ("Enter the total number of years you're investing this amonut.") 
totYear = int(input()) 

print("Year  Interest") 
for year in range(totYear): 
    total=totYear*interest*princ 
    print (totYear,"  $",total) 
    totYear+=1 

if total<100: 
    print("That is not too much interest!") 
else: 
    print("This interest really adds up!") 

これで出力画面:

Enter the principal amount. 
10 
Enter the interest rate. 
5 
Enter the total number of years you're investing this amonut. 
5 
Year  Interest 
5  $ 250.0 
6  $ 300.0 
7  $ 350.0 
8  $ 400.0 
9  $ 450.0 
This interest really adds up! 

は、任意の助けをありがとう!

+0

あなたはその範囲を通過する変数であるので、 'year'を印刷したいです。私は 'totYear'をインクリメントする必要はないと思います。 –

+0

は、' totYear'の代わりに 'year'を印刷してみてください。 – greggo

答えて

0

これは出力しますか?

Enter the principal amount. 
10 
Enter the interest rate. 
5 
Enter the total number of years you're investing this amonut. 
5 
Year  Interest 
0  $ 250.0 
1  $ 300.0 
2  $ 350.0 
3  $ 400.0 
4  $ 450.0 
This interest really adds up! 

ので、あなたはこれでprint (totYear," $",total)を交換する必要がある場合:

print (year," $",total)

また、あなたはそれがために初期化されるようyearを初期化する必要はありません。あなたが年として年にループでごtotYearを変更する必要が

0

まずカウンター

ですその後、私はあなたが(入力を(intに等しいtotYear設定していると信じて最後の増分

+0

おかげで、それはすべての繰り返しで同じ年(totYear)を計算するのに役立ちました。今では、毎年を計算に入れることで正しい結果が得られます。出力がtotYearまでを含むようにするにはどうすればよいですか?私は、彼らが最終年度にどのような利益を得たのかを示したいが、前にはそれを切り捨てる。 –

+0

次に、forループを範囲の年(toYear + 1)に変更します。 –

+0

私が使用した修正は、totYear変数を宣言するときにユーザー入力に「+1」を追加しました。範囲関数は開始値から終了値までしか読み込まないので、 –

-1

を削除します) )これが、ユーザーが入力した年数からカウンターが始まる理由です。

int(input())と同じ数の別の変数を作成し、range(totYear)の代わりにrange(numYears)を設定すると便利です。

#variable that gets number of years user inputs 
numYears = 0; 
#Get the total amount of years principal is invested. 
print ("Enter the total number of years you're investing this amonut.") 
numYears = int(input()) 

print("Year  Interest") 
for year in range(numYears): 
total=totYear*interest*princ 
print (totYear,"  $",total) 
totYear+=1 
0

これは前の質問で私があなたに与えたループで、printステートメントは年を含むように更新されています。あなたがすでに計算した「+1」調整を追加しました。希望どおりにフォーマットします。

princ = 10000 
interest = 0.10 
totYears = 5 

for year in range(1, totYears+1): 
    total = year * interest * princ 
    print (year, total) 

出力:

1 1000.0 
2 2000.0 
3 3000.0 
4 4000.0 
5 5000.0 
関連する問題