http:^^www.cs.wisc.edu^~mbirk^cs302^format_dollars.html
来自「This data set contains WWW-pages collect」· HTML 代码 · 共 120 行
HTML
120 行
Date: Mon, 11 Nov 1996 17:01:23 GMTServer: NCSA/1.5Content-type: text/htmlLast-modified: Tue, 01 Oct 1996 20:08:43 GMTContent-length: 2431<html><head><title>Formatting Dollar Amounts in Program 2</title></head><body><h2>Formatting Dollar Amounts in Program 2</h2>You might be wondering how to line up the dollar amounts for Program 2 sothat everything looks nice like the example output. This involves twosteps:<p><ol> <li> Telling the computer to print floating-point nuumbers using exactly two decimal places <li> Making the dollar amounts line up at their decimal point</ol><p>The necessary material is described on pages 51 and 232 of theSavitch text (pages 65-66 of Perry & Levin). However, I'll explainhere just what you need to know for the assignment.<p>Consider this silly little program:<p><pre>#include <iostream.h>int main (){ double amount_deposited = 100.0; double cash_received = 9.71; cout << "Amount deposited: $" << amount_deposited << endl; cout << "Cash received: $" << cash_received << endl; cout << "Net deposit: $" << (amount_deposited - cash_received) << endl; return 0;}</pre><p>When run, it produces the following output:<p> <pre>Amount deposited: $100Cash recieved: $9.71Net deposit: $90.29</pre><p>But what we <i>want</i> is something more like this:<p><pre>Amount deposited: $ 100.00Cash recieved: $ 9.71Net deposit: $ 90.29</pre><p>We can modify the above program to achieve this:<p><pre>#include <iostream.h>#include <iomanip.h>int main (){ // Force two decimal places (see p. 51 of Savitch text) cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); double amount_deposited = 100.0; double cash_received = 9.71; // The "setw(7)" below causes the next thing printed to // have a width of seven cout << "Amount deposited: $" << setw(7) << amount_deposited << endl; cout << "Cash received: $" << setw(7) << cash_received << endl; cout << "Net deposit: $" << setw(7) << (amount_deposited - cash_received) << endl; return 0;}</pre><p>Note the extra <tt>#include<iomanip.h></tt> directive at the top of theprogram. This is necessary to use <tt>setw</tt>.<hr><i><a href="mailto:mbirk@cs.wisc.edu">mbirk@cs.wisc.edu</a></i></body></html>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?