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 <string> /*
* Function: getInteger
* Usage: int n = getInteger(prompt);
* ----------------------------------
* Reads a complete line from <code>cin</code> 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
* <code>prompt</code> string is printed before reading the value.
*/ int getInteger(std::string prompt = ""); /*
* Function: getReal
* Usage: double x = getReal(prompt);
* ----------------------------------
* Reads a complete line from <code>cin</code> 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 <code>prompt</code> 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 <code>cin</code> 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
* <code>prompt</code> 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 <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include "simpio.h"
using namespace std; /*
* Implementation notes: getInteger, getReal
* -----------------------------------------
* Each of these functions reads a complete input line and then uses the
* <sstream> 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 <iostream>
#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 <iostream>
#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循环)可以解决的问题都可以用递归来解决。
  • 大部分的问题用递归解决的也可以使用迭代来解决
  • 当可以选择的时候,我们应该优先选择迭代,而不是递归。
注:有些问题我们只能用递归来解决。


【stanford C++】——2.C++中函数的更多相关文章

  1. 如何理解javaSript中函数的参数是按值传递

    本文是我基于红宝书<Javascript高级程序设计>中的第四章,4.1.3传递参数小节P70,进一步理解javaSript中函数的参数,当传递的参数是对象时的传递方式. (结合资料的个人 ...

  2. Swift3中函数的使用

    前言:前不久,Swift语言也更新到了3.0版本,对编程有一定基础的朋友一定不会对函数这个概念陌生.而Swift语言中的函数也是大同小异的,今天就跟着小编来学习一下Swift3中函数的不一样的用法. ...

  3. JavaScript中函数函数的定义与变量的声明<基础知识一>

    1.JavaScript中函数的三种构造方式 a.function createFun(){ } b.var createFun=function (){ } c.var createFun=new ...

  4. oracle中函数和存储过程的区别和联系【转载竹沥半夏】

    oracle中函数和存储过程的区别和联系[转载竹沥半夏] 在oracle中,函数和存储过程是经常使用到的,他们的语法中有很多相似的地方,但也有自己的特点.刚学完函数和存储过程,下面来和大家分享一下自己 ...

  5. string.h文件中函数用法

    下面为string.h文件中函数的详细用法: strcpy函数名:strcpy功 能: 拷贝一个字符串到另一个用 法: char *strcpy(char *destin, char *source) ...

  6. 三种语言(c++、as、lua)中函数的差异性

    对于不同的语言, 尤其是静态语言和动态语言, 对于函数的定义(即如何看待一个函数)和处理截然不同.具体来说可以分为两类: 1.将函数视为第一类型值, 即函数和其他的对象一样, 都是语言中一个普通的对象 ...

  7. C/C++中函数参数传递详解(二)

    昨天看了内存管理的有关内容,有一点了解,但不是很深入,发现之前写代码时有很多细节问题没有注意到,只知道这样做可以实现功能,却不知道为什么可以这样,对于采用自己的方法造成的隐患也未知,更不晓得还有其他方 ...

  8. 动态链接库中函数的地址确定---PLT和GOT [转]

    前面写过动态链接库 延迟绑定的一篇博文,那篇文章我非常喜欢,但是当时刚搞清楚,自己写的比较凌乱,我最近学习了Ulrich Drepper的How to write share library,学习了几 ...

  9. Javascript中函数的四种调用方式

    一.Javascript中函数的几个基本知识点: 1.函数的名字只是一个指向函数的指针,所以即使在不同的执行环境,即不同对象调用这个函数,这个函数指向的仍然是同一个函数. 2.函数中有两个特殊的内部属 ...

  10. JavaScript中函数的形参和实参的实现原理剖析

    我们都知道JS里面参数的传递是可以不一样的,比如我们有一个函数: <script type="text/javascript"> function one(a,b,c) ...

随机推荐

  1. C语言双向链表

    原文:C语言双向链表 今天写了点双向链表的各种操作,写插入的时候费了点时间,不过,现在看来还是值得耗费那点时间去写的,这种小东西应该能信手拈来才行啊. /*双向链表*/ #include <st ...

  2. java设计模式之八代理模式(Proxy)

    其实每个模式名称就表明了该模式的作用,代理模式就是多一个代理类出来,替原对象进行一些操作,比如我们在租房子的时候回去找中介,为什么呢?因为你对该地区房屋的信息掌握的不够全面,希望找一个更熟悉的人去帮你 ...

  3. installshield制作的安装包卸载时提示重启动的原因以及解决办法

    原文:installshield制作的安装包卸载时提示重启动的原因以及解决办法 有时候卸载installshield制作的安装包程序,卸载完会提示是否重启电脑以完成所有卸载,产生这个提示的常见原因有如 ...

  4. 19.最经济app发短信的方法

    在创业团队.一个重要的原则是能省就省,该花的花,明智地使用金钱. 今的app,为了获取用户的社交关系.须要用户的手机号注冊. 用手机号注冊就涉及到一个发送短信验证码的问题,那怎么才干在短信服务上投入最 ...

  5. IT行业新名词--透明手机/OCR(光学字符识别)/夹背电池

    透明手机 机身设计的一大关键部分是可替换玻璃的使用,利用导电技术,在看不到线路的环境下,让LED发光. 这样的玻璃内含液晶分子,对于内容的显示则是通过电流对分子的刺激来实现.当手机断电后,分子位置会随 ...

  6. MVC6 - 视图组建

    MVC6 - 视图组建 VS2015 PERVIEW中可以创建MVC6 项目. 我们可以 发现有几大亮点. 首先我们看目录结构: 当前项目包含两个主要的文件夹:Solution Items .src ...

  7. Extjs grid分页多选记忆功能

    很多同事在用extjs grid做分页的时候,往往会想用grid的多选功能来实现导出Excel之类的功能(也就是所谓的多选记忆功能),但在选选择下一页的时候 上一页选中的已经清除 这是因为做分页的时候 ...

  8. 用css样式围剿等高列问题(转载)

    明修栈道暗度陈仓 该秘籍的心法只有十二个字:”隐藏容器溢出,正负内外边距.”看完下面的几行代码,再看这句话你真的可以看到圣光! 隐藏容器溢出.将外层容器的溢出设为隐藏: .container { ov ...

  9. Android项目---TouchListener

    public static interface View.OnTouchListener android.view.View.OnTouchListener Known Indirect Subcla ...

  10. 关于如何惟一地标识一台Android设备的综合性讨论

    想必大家在开发Android项目的时候,多多少少会遇到“如何惟一地标识一台Android设备”等类似的问题.不只是以前,即使是现在乃至可以预见的将来,这个问题都将一直存在. 如果大家使用搜索工具搜索的 ...