博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【stanford C++】——2.C++中函数
阅读量:4685 次
发布时间:2019-06-09

本文共 5666 字,大约阅读时间需要 18 分钟。

1. main()函数


C++程序从main()函数开始执行:

int main(){	/* ... code to execute ... */}

按照约定,main函数应该返回0,除非程序遇到错误。

 

在C++中,使用cout来显示文本,同时使用cin接受输入。

由于技术原因,已经实现了一些函数用于输入。

库“simpio.h”包含用于读取输入的方法:

int getInteger(string prompt = "");double getReal(string prompt = "");string getLine(string prompt = "");

代码如下:

simio.h为:

 

/* * File: simpio.h * -------------- * This file exports a set of functions that simplify input/output * operations in C++ and provide some error-checking on console input. */#ifndef _simpio_h#define _simpio_h#include 
/* * Function: getInteger * Usage: int n = getInteger(prompt); * ---------------------------------- * Reads a complete line from
cin and scans it as an * integer. If the scan succeeds, the integer value is returned. If * the argument is not a legal integer or if extraneous characters * (other than whitespace) appear in the string, the user is given * a chance to reenter the value. If supplied, the optional *
prompt string is printed before reading the value. */int getInteger(std::string prompt = "");/* * Function: getReal * Usage: double x = getReal(prompt); * ---------------------------------- * Reads a complete line from
cin and scans it as a * floating-point number. If the scan succeeds, the floating-point * value is returned. If the input is not a legal number or if * extraneous characters (other than whitespace) appear in the string, * the user is given a chance to reenter the value. If supplied, the * optional
prompt string is printed before reading the value. */double getReal(std::string prompt = "");/* * Function: getLine * Usage: string line = getLine(prompt); * ------------------------------------- * Reads a line of text from
cin and returns that line * as a string. The newline character that terminates the input is * not stored as part of the return value. If supplied, the optional *
prompt string is printed before reading the value. */std::string getLine(std::string prompt = "");#endif

simpio.c代码如下:

 

 

/* * File: simpio.cpp * ---------------- * This file implements the simpio.h interface. */#include 
#include
#include
#include
#include "simpio.h"using namespace std;/* * Implementation notes: getInteger, getReal * ----------------------------------------- * Each of these functions reads a complete input line and then uses the *
library to parse that line into a value of the desired type. * If that fails, the implementation asks the user for a new value. */int getInteger(string prompt) { int value; string line; while (true) { cout << prompt; getline(cin, line); istringstream stream(line); stream >> value >> ws; if (!stream.fail() && stream.eof()) break; cout << "Illegal integer format. Try again." << endl; if (prompt == "") prompt = "Enter an integer: "; } return value;}double getReal(string prompt) { double value; string line; while (true) { cout << prompt; getline(cin, line); istringstream stream(line); stream >> value >> ws; if (!stream.fail() && stream.eof()) break; cout << "Illegal numeric format. Try again." << endl; if (prompt == "") prompt = "Enter a number: "; } return value;}/* * Implementation notes: getLine * ----------------------------- * The getLine function simply combines the process of displaying a * prompt and reading an input line into a single call. The primary * reason for including this function in the library is to ensure * that the process of reading integers, floating-point numbers, and * strings remains as consistent as possible. */string getLine(string prompt) { string line; cout << prompt; getline(cin, line); return line;}

如果没有指定提示的话,这些函数有缺省的参数,它将使用空字符串。

 

 

C++函数

C++中的函数与Java中的方法类似。

  • 代码片段执行一些任务
  • 能接受参数
  • 能返回值

C++函数的语法与Java中的类似:

return-type function-name(parameters){	/* ... function body ... */}

注:return-type前面没有public或private。

 

不想一些其他语言(java或C#),C++有one-pass编译器。

如果一个函数没有被声明,当使用的时候,将会有编译错误。

举例:树根(digital root)

一个数的树根,可以按如下步骤计算:

1)若为一位数,则它自身就是该数的树根。

2)若为多位数,加上所有的数字,并重复。

例如,5的树根为5。

  42->4+2 = 6,所以42的数根为6。

 137->1+3+7 = 11, 11->1+1 = 2,所以137的树根为2.

代码实现如下:

 

/* File: digital-roots.cpp * * A program to compute digital roots. */#include 
#include "simpio.h"using namespace std;int digitalRoot(int num);int sumOfDigits(int n);int main() { while (true) { int value = getInteger("Enter an integer: "); cout << value << " has digital root " << digitalRoot(value) << endl; }}int digitalRoot(int n) { if (n < 10) { return n; } else { return digitalRoot(sumOfDigits(n)); }}int sumOfDigits(int n) { if (n < 10) { return n; } else { return (n % 10) + sumOfDigits(n / 10); }}

 

2.递归的思考


举例:Factorial 

代码实现如下:

 

/* File: factorial.cpp * * A program that computes n!. */#include 
#include "simpio.h"using namespace std;/* Computes n!. */int factorial(int n);int main() { int num = getInteger("Enter a number: "); cout << num << "! = " << factorial(num) << endl; return 0;}int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); }}

使用递归解决一个问题需要两步:

 

 

  • 首先,对于简单的情况,决定如何解决——基本情况
  • 然后,决定如何把大的问题划分为小的实例进行处理——递归分解
递归的伪代码如下:
if(problem is sufficiently simple) {	Directly solve the problem.	Return the solution.} else{	Split the problem up into one or more smaller	problems with the same structure as the original.	Solve each of those smaller problems.	Combine the results to get the overall solution.	Return the overall solution.}
递归与迭代的比较:
  • 任何用迭代(for/while循环)可以解决的问题都可以用递归来解决。
  • 大部分的问题用递归解决的也可以使用迭代来解决
  • 当可以选择的时候,我们应该优先选择迭代,而不是递归。
注:有些问题我们只能用递归来解决。

 

 

 

 

 

 

转载于:https://www.cnblogs.com/jiangu66/p/3167717.html

你可能感兴趣的文章
iOS/Android 微信及浏览器中唤起本地APP
查看>>
[Usaco2005 nov]Grazing on the Run 边跑边吃草 BZOJ1742
查看>>
Spark 各个组件关系
查看>>
测试准入准出标准
查看>>
区块链学习笔记01(基本介绍)
查看>>
EF多个表映射
查看>>
J2EE项目集成SAP的BO报表
查看>>
SpringBoot--外部配置
查看>>
项目开发总结报告(GB8567——88)
查看>>
BZOJ1930: [Shoi2003]pacman 吃豆豆
查看>>
SSH加固
查看>>
端口扫描base
查看>>
iOS IM开发的一些开源、框架和教程等资料
查看>>
FansUnion:共同写博客计划终究还是“流产”了
查看>>
python 二维字典
查看>>
编译原理实验一
查看>>
Git for Android Studio 学习笔记
查看>>
pip 警告!The default format will switch to columns in the future
查看>>
Arrays类学习笔记
查看>>
实验吧之【天下武功唯快不破】
查看>>