士兵买香蕉

题目大意:

A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).

He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?

输入:

输入三个数,N,K,W,1<=K,W<=1000,0<=N<=10^9,N是第一个香蕉的费用,K是士兵拥有的money,W是士兵要买的香蕉个数。

输出:

士兵需要向朋友借多少(q)钱才能买到自己想买的香蕉

 

题目分析:

1、依次算出所有香蕉需要花多少钱sum;

2、用sum跟K比较(两种情况:K大于等于sum不用借,否则要借)

3、q=K-sum;

源代码:

 1 #include<iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     int k, n, w, sum = 0, q;
 6     cin >> k >> n >> w;
 7     for (int i = 1; i <= w; i++)
 8         sum += i*k;
 9     if (n == sum||n>sum)
10         cout << "0" << endl;
11     else
12     {
13         q = sum - n;
14         cout << q << endl;
15     }
16     
17     return 0;
18 
19 }

心得:题目比较简单,但各种情况要考虑到,写代码时最开始就只想到要借钱的那一部分,没有想到还有不借的。犯的错误比较低级。。。。。继续加油吧!O(∩_∩)O~~~

 

 

posted @ 2015-07-16 19:44  白一  阅读(354)  评论(0编辑  收藏  举报