




已阅读5页,还剩53页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
* 清单2-4 */ File: coins.cpp/ Determines the values of a coin collection#include #include using namespace std;int main()string name;/ input: nieces first nameint pennies;/ input: count of penniesint nickels;/ input: count of nickelsint dollars;/ output: value of coins in dollarsint change;/ output: value of coins in centsint totalCents; / total cents represented/ Read in your nieces first name.cout name;/ Read in the count of nickels and pennies.cout nickels;cout pennies;/ Compute the total value in cents.totalCents = 5 * nickels + pennies;/ Find the value in dollars and change.dollars = totalCents / 100;change = totalCents % 100;/ Display the value in dollars and changecout Good work name ! endl;cout You collection is worth dollars dollars and change cents. endl; return 0;*将英里转化为千米的程序的批处理版本*/ File: milesBatch.cpp/ Converts distance in miles to kilometers.#include using namespace std;int main()const float KM_PER_MILE = 1.609;/ 1.609 km in a milefloat miles,/ input: distance in miles kms;/ output: distance in kilometers/ Get the distance in miles.cin miles;cout The distance in miles is miles endl;/ Convert the distance to kilometers.kms = KM_PER_MILE * miles;/ Display the distance in kilometers.cout The distance in kilometers is kms endl;return 0;*string操作说明*/ File: stringOperations.cpp/ Illustrates string operations#include #include using namespace std;int main()string firstName, lastName;/ inputs - first and last names string wholeName;/ inputs - whole namestring greeting = Hello ;/ output - a greeting string/ Read first and last names.cout firstName;cout lastName;/ Join names in whole namewholeName = firstName + + lastName;/ Display results cout greeting wholeName ! endl;cout You have (wholeName.length() - 1 ) letter in your name. endl;/ Display initialscout Your initials are firstName.at(0) lastName.at(0) endl;return 0;*/ File: testScale.cpp/ Tests function scale #include #include using namespace std;/ Function prototype float scale(float, int);int main()float num1;int num2;/ Get value from num1 and num2cout num1;cout num2;/ Call scale and display the result.cout Result of call to function scale is scale(num1, num2)/ actual arguments endl; return 0;float scale(float x, int n) / formal argumentsfloat scaleFactor;scaleFactor = pow(10, n);return ( x * scaleFactor);清单6-1 测试函数moneyToNumberString/ 此函数具有删除出现在它的字符串中的美元符号和所有逗号的功能/ File: moneyToNumberTest.cpp/ Tests function moneyToNumberString #include #include using namespace std; / Function prototypevoid moneyToNumberString(string&);int main()string mString;/ input - a mmoney string cout mString;moneyToNumberString(mString);cout The dollar amount as a number is mString = 0 & posComma moneyString.length() / Is posComma valid ?moneyString.erase(posComma, 1);/ Remove ,posComma = moneyString.find(,);/ Find next ,/ endmoneyToNumberString清单6-2 计算求和与平均值的函数/ File: computeSumAve.cpp/ Computes and print the sum and average of a collection of date.#include using namespace std;/ Function used ./ Computes sum of datefloat computeSum(int);float computeAve(int, float);void printSumAve(int, float, float);int main()int numItems;/ input - number of items to be addedfloat sum;/ output - accumulated sum of datafloat average;/ output - average of the data / Read the number of items to process.cout numItems;/ Compute the sum of the data.sum = computeSum(numItems);/ Compute the average of the data.average = computeAve(numItems, sum);/ Print the sum and the average.printSumAve(numItems, sum, average);return 0;/ Computes the sum of data.float computeSum(int numItems)float item;float sum;/ Read each data item and accumulate it in sum.sum = 0.0;for(int count = 0; count numItems; count+)cout item;sum += item;return sum; / end computeSum/ Computes average of datafloat computeAve(int numItems, float sum)/ Compute the average of the data.if (numItems 1)/ test for invalid inputcout Invalid values for numItems = numItems endl;cout Average not computed. 0)cout The number of items is numItems endl;cout The sum of the data is sum endl;cout The average of the data is average endl;elsecout Invalid number of items = numItems endl;cout Sum and average are not defined. endl;cout No prints done. Execution terminated. endl; / end if / end printSumAve清单6-2 一般求和与平均值问题的样例运行结果Enter the number of items to process: 3Enter a number to be added: 5Enter a number to be added: 6Enter a number to be added: 17The number of items is 3The sum of the data is 28The average of the data is 9.33333Press any key to continue清单6-3 对3 个数据进行排序的函数/ File: sort3Numbers.cpp/ Read three numbers and sorts them in ascending order.#include using namespace std;/ Function used ./ Sorts a pair of numbersvoid order(float& ,float&);int main()float num1, num2, num3;/ user input - numbers to sort/ Read 3 numbers.cout num1 num2 num3;/ Sort them.order(num1, num2);/ order data in num1 & num2 order(num1, num3);/ order data in num1 & num3order(num2, num3);/ order data in num2 & num3/ Display results.cout The three numbers in order are: endl;cout num1 num2 num3 y)temp = x;x = y;y = temp; / end order 清单 6-4 测试getFrac函数_/ 此函数有用户输入一个简分数,并通过两个int类型的输出参数返回分子和分母/ File: testGetFrac.cpp/ Test function getFrac#include using namespace std;void getFrac(int& , int&);int main()int num, denom;/ intput - fraction numerator and denominatorcout Enter a common fraction as 2 integers separated by a slash: ;getFrac(num, denom);cout Fraction is num / denom numerator slash denominator; / end order 清单6-5 计算和与平均值的函数/ File: computeSumAve.cpp/ Test function computeSumAve#include using namespace std;void computeSumAve(float, float, float&, float&);int main()float x, y, sum, mean;cout x y;/ Compute the sum and the average of x and ycomputeSumAve(x, y, sum, mean);/ Display resultscout Sum is sum endl;cout Average is mean endl;return 0;void computeSumAve(float num1, float num2, float& sum, float& average)sum = num1 + num2;average = sum / 2.0; / end order 清单7-1 ASCII码排列顺序程序实例/ File: collate.cpp/ Display part of the character collating sequence#include using namespace std;int main()const MIN = 32;/ smallest numeric code const MAX = 126;/ largest numeric codechar nextChar;/ output - character form of next code/ Display sequence of characters.for(int nextCode = MIN; nextCode = MAX; nextCode+)nextChar = char(nextCode); cout nextChar; if (nextChar = Z)cout endl;cout endl;return 0;清单 7-2 digitToNumber函数#include using namespace std;digitToNumber(char);int main()char ch1;cout ch1;cout the number to the digit is: digitToNumber(ch1);cout endl;return 0;int digitToNumber(char ch)if(isdigit(ch)return (int(ch) - int(0);elsereturn -1;清单8-2 处理流中的各个字符_ / File : countChars.cpp/ Counts number of characters in a line and lines in a stream#include #include using namespace std;#define ENDFILE CRRL-Zint main()const char NWLN = n;char next;/ next character in current lineint charCount;/ number of character in current line int lineCount;/ keeps track of number of lines in filelineCount = 0;cout Enter a line or press ENDFILE : ;cin.get(next);/ get first char of new linewhile(!cin.eof()charCount = 0;/ initialize character count for new linewhile(next != NWLN)cout.put(next);charCount+;/ Increment character count.cin.get(next);/ Get next character. / end inner while cout.put(NWLN);lineCount+;cout Number of characters in line lineCount is charCount endl;cout Enter a line or press ENDFILE : ;cin.get(next);/ Get next character. / end outer while cout endl endl Number of lines processed is lineCount endl;return 0;清单8-3 拷贝文件/ File : copyFile.cpp/ Copies file InData.txt to file OutData.txt#include #include / for external file streams#include / for definition of EXIT_FAILUREusing namespace std;/ Associate stream object with external file names#define inFile D:My Documentsnspk1.txt/ directory name for inFile #define outFile D:My DocumentsOutData.txt/ directory name for Outfile / Function used ./ Copies one line of text int copyLine(ifstream&, ofstream&);int main()int lineCount;/ output: number of lines processed ifstream ins;/ ins is an input stream ofstream outs;/ outs is an output stream/ Open input and output file, exit on any errorins.open(inFile);/ connnect ins to file inFileif(ins.fail()cerr * ERROR: Cannot open inFile for input. endl;return EXIT_FAILURE;/ failure returnouts.open(outFile);/ connect outs to file outFile if(outs.fail()cerr * ERROR: Cannot open outFile for output. endl;return EXIT_FAILURE;/ failure return / Copy each character from inData to outData.lineCount = 0;while(!ins.eof()if(copyLine(ins,outs) != 0)lineCount+;/ Display a message on the screen.cout Input file copied to output file. endl;cout lineCount lines copied. endl;ins.close();/ close input file streamouts.close();/ close poutput file streamreturn 0; / Copy one line of text from one file to another int copyLine(ifstream& ins, ofstream& outs)const char NWLN = n; / newline character char nextCh;/ inout: character buffer int charCount = 0;/ Copy all data character from stream ins to stream outs.ins.get(nextCh);while(nextCh != NWLN) & !ins.eof()outs.put(nextCh);charCount+;ins.get(nextCh); / end while/ If last character read was NWLN write it to outs.if(!ins.eof()outs.put(NWLN);charCount+;return charCount; / end copyLine 可以使用下面的代码上面主函数的循环,在头文件中加入#include string line;lineCount = 0;getline(ins, line);while(line.length() != 0)lineCount+;outs line endl;getline(ins, line);清单8-4 计算员工工资及总工资_/ File : payrollFile.cpp/ Creates a company employee payroll file/ Computes total company payroll amount#include #include / required for file streams#include / for definition of EXIT_FAILURE#include using namespace std;/ Associate stream object with external file names#define inFile D:My DocumentsEmpFile.txt/ directory name for inFile #define outFile D:My DocumentsSalary.txt/ directory name for Outfile / Function used ./ Processs all employees and compute total float processEmp(ifstream&, ofstream&);int main()ifstream eds;/ input: employee data stream ofstream pds;/ output: payroll data streamfloat totalPayroll;/ output: total payroll/ Prepare files.eds.open(inFile);/ connnect ins to file inFileif(eds.fail()cerr * ERROR: Cannot open inFile for input. endl;return EXIT_FAILURE;/ failure returnpds.open(outFile);/ connect outs to file outFile if(pds.fail()cerr * ERROR: Cannot open outFile for output. endl;eds.close();return EXIT_FAILURE;/ failure return / Process all employees and compute total payrol.totalPayroll = processEmp(eds, pds);/ Display resultcout Total payroll is $ totalPayroll firstName lastName hours rate;while(!eds.eof()salary = hours * rate;pds firstName lastName salary firstName lastName hours rate; / end while return payroll; / end processEmp程序运行结果:Salary.txt文件中的内容:Jim Baxter 257.375Adrian cCybriwsky 260Ayisha Mertens 160Total payroll is $677.375清单8-5 使用函数getline和ignore 读取并处理这个文件的所有记录_/ File : payrollFile.cpp/ Creates a company employee payroll file/ Computes total company payroll amount#include #include / required for file streams#include / for definition of EXIT_FAILURE#include using namespace std;/ Associate stream object with external file names#define inFile D:My DocumentsEmpFile.txt/ directory name for inFile #define outFile D:My DocumentsSalary.txt/ directory name for Outfile / Function used ./ Processs all employees and compute total float processEmp(ifstream&, ofstream&);int main()ifstream eds;/ input: employee data stream ofstream pds;/ output: payroll data streamfloat payroll;float hours;float rate;float salary;string name;/ Prepare files.eds.open(inFile);/ connnect ins to file inFileif(eds.fail()cerr * ERROR: Cannot open inFile for input. endl;return EXIT_FAILURE;/ failure returnpds.open(outFile);/ connect outs to file outFile if(pds.fail()cerr * ERROR: Cannot open outFile for output. hours rate;salary = hours * rate;pds name salary endl; payroll += salary;eds.ignore(
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 服装知识考试题目及答案
- 液流电池制造项目节能评估报告
- 音乐鉴赏基础试题及答案
- 团务基础试题及答案
- 数字化财务审计的创新方法与技术手段
- 包装物流中心建设项目经济效益和社会效益分析报告
- 羽毛球拍生产线项目风险评估报告
- 风电场项目社会稳定风险评估报告
- 2025年小餐馆员工的劳动合同模板
- 智慧康养中心综合建设项目经济效益和社会效益分析报告
- 穴位按摩法操作评分标准
- 充电站运营管理制度(参考模板)
- 体育与健康教学设计《手倒立前滚翻》
- NISP一级考前模拟训练题库200题(含答案)
- JJG 20-2001标准玻璃量器
- 2024外研版初中英语单词表汇总(七-九年级)中考复习必背
- 《大数据平台部署与运维》课程标准(含课程思政)
- 英语中的时间表达(示范课例)
- 脊柱外科进修汇报
- 《史记》上册注音版
- 苏州大学文学院语言学纲要课程笔记
评论
0/150
提交评论