SRM154 Div.2 Easy ProfitCalculator
さっき解きました。
結構楽で10分ぐらいしかかからなかった。
stringからdoubleへの変換
問題文はコレ
PROBLEM STATEMENT Margin is defined as the percentage of the selling price of an item or group of items which is profit. For example, if an item costs $80 and is sold for $100, then there is $20 profit, or 20% margin. You will be given a vector, items, which is all of the items sold in a single transaction. Each string in items will be formatted as follows: "nnn.nn nnn.nn" (quotes for clarity), where each n is a digit between '0' and '9' inclusive. Each string will be exactly 13 characters in length. The first number listed is the price the customer paid for the item. The second number is what the cost to the store of the item was. You will create a class ProfitCalculator with a method percent which will calculate the percentage of margin on the transaction and return it as an int, rounded down to the greatest integer less than the actual value. For example, let's say you were given the following vector : { "012.99 008.73", "099.99 050.00", "123.45 101.07" } The total cost is $159.80. The total price is $236.43. That means $76.63 was made on this sale. This would be a 32.41128% margin. Since we are rounding down, you would return 32. DEFINITION Class:ProfitCalculator Method:percent Parameters:vector Returns:int Method signature:int percent(vector items) NOTES -The cost for some items may be greater than the price they was sold for. However, the sum of the prices of all the items in the transaction will be greater than the sum of the costs of all items. CONSTRAINTS -items will contain between 1 and 50 elements, inclusive. -Every string in items will be exactly 13 characters in length. -Every string in items will be formatted as "nnn.nn nnn. nn" where each n is a digit between '0' and '9' inclusive, thus the range for each price will be between "000.00" and "999.99" inclusive (all quotes for clarity). -The total price of all items will be greater than the total cost of all items. -The total price of all items will be greater than 0. -The percent of margin, prior to rounding, will not be within 1e-5 of an integer.
なんか問題としてはSRM153とそう変わらないんですが、stringからdoubleへの変換が。。。
これにはistringstreamを使いますが、ネックはcinと使い方があまり変わらないこと。
つまりis >> x >> y;とやれば"0234.12 03453.2"がx=234.12、y=3453.2になったりするわけ。
この問題は気にしなくていいけど、あとこれの欠点はcinと同じようにdouble型の精度があらかじめ決められていること。
これもcinとおなじほうほうで解決できる。
あと注意したことはキャストを式全体に掛けているところとか、istringstreamの初期化の位置かな。
正解のコード。
class ProfitCalculator { public: int percent(vector <string> items) { double tcost=0, tprice=0, cost, price, profit; int ret; for (int i=0; i<items.size(); i++) { istringstream is; is.str(items[i]); is >> price >> cost; // cout << cost << " " << price << endl; tcost += cost; tprice += price; } profit = tprice - tcost; ret = (int)(profit/tprice*100); return ret; } };
では!普通の生活に戻りたいと思います(笑)