C++第五章函数

书上的点:

这次直接写写画画了,遇到的bug也就直接敲了,忘记记录了,好在都在书上,所以勾画一下,提一下。发现每一章后面的小结,都蛮有意思的。可以抄一遍。

1、返回值的函数成为返回值函数(value-returning function),不返回值的函数成为void函数 (void function

2、实际参数(actual parameter) 也称 自变量 argument

3、参数列表(parameter list)指明了函数的参数类型、次序和数量。函数名和参数列表一起构成了函数签名(function signature)。

4、主函数与其他函数的唯一差别在于,它是由操作系统来调用的,用于启动程序的执行。

5、按值方式(pass-by-value)传递参数。当调用一个带参数的函数时,实参的值被传递给形参,这种参数传递方式称为按值方式。无论函数中形参的值如何改变,实参变量的值都不会受影响。

6C++提供了一种特殊的变量类型,称为引用变量(reference variable),将函数形参声明为此种类型的变量,形参将成为原变量的一个引用(而不是拷贝)。一个引用变量实质上是另一个变量的的一个别名,任何对引用变量的改变实际上都会作用到原变量上。为声明一个引用变量,应在变量名钱放置一个“与符号”(&)。

7、按值方式和按引用方式是函数参数传递的两种方式。按值方式将实参的值传递给一个无关的变量(形参),而按引用方式中形参与实参共享相同的变量。从语义的角度来看,按引用方式可以理解为按共享方式(pass-by-sharing)。

8、然后是书上的一个应该是编译通不过的,但是书上却给出了结果。。。

大概就是:

void f(double &p){

p++;

}

int main(){

double a = 1.0;

int b = 1;

f(a);

f(b);//这个是跑不了的。

}

 

9、二义调用:有事,对一个函数调用可能有两个或更多的与之匹配的函数定义,而编译器无法确定那个匹配更为京珠你,这称为二义调用(ambiguous invocation)。

10、在函数调用之前声明一个函数原型(funciton prototype)。一个函数原型就是一个没有函数实现(函数体)的单纯的函数声明,函数的实现在稍后的程序中将会给出。

11、如果函数的参数中,有的设置默认值,有的没有,那么带默认值的参数应该放在参数列表的末尾。

12、变量的作用域(scope of a variable)。一个变量的作用域就是能够引用该变量的程序范围。函数内部定义的变量成为局部变量(local variable

13、如果一个局部变量与一个全局变量同名,使用::globalVariable可以访问全局变量,::运算符称为一元作用域解析(unary scope resolution)运算符。

14、函数抽象(funciton abstraction)就是将函数的使用和实现分离。

15、信息隐藏(information hiding)或封装(encapsulation

16、分而治之(divide and conquer) 逐步求精 (stepwise refinement

17、要编写一个程序,我们应该如何入手?立即开始编码?程序员新手通常会这样做,开始就试图从细节着手求解问题。虽然在最终程序中西街是很重要的,但在开始阶段就考虑西街会阻塞问题的求解进程。为是问题求解流程尽可能顺畅,我们求解这个问题是,使用函数抽象思想将设计和细节分离,最后在实现细节。

18、自顶向下方法top-down approach 自底向上方法bottom-up approach

19、对于还未实现的函数,可用桩函数(stub)代替之。所谓桩函数就是一个简单的但并不完整的函数版本。

20、挡视线一个大型程序时,我们应该使用自顶向下方法或者自底向上方法,不要试图一下子完成整个程序的编码。这两种方法看起来会花费更多的时间编码(因为需要反复的编译和不断地测试程序的渐进版本),但实际上会节省总时间,并且使调试更为容易。

21、内联函数(inline function)总是接触到这个东西,但貌似总也不知道这是啥意思。使用函数来实现程序可以是程序更为易读、易于维护,但是函数调用有额外的运行时开销(即将参数和CPU寄存器亚茹调用栈,以及在函数间切换控制所花费的时间)。C++提懂了内联函数功能,这样可以便面函数调用的开销。内联函数是不会被调用的,实际上,编译器将其代码复制到了每个调用点上。

这些话比较冠冕。

实际上,我们之前写函数都是调用方式的,但是内联函数的本质是,不产生调用关系。而是在编译阶段,就把inline function 的函数体拿出来,代替函数调用。也就是用内联函数函数体,来代替当前函数调用的这行代码,也就是用一大段代码来替换一行代码。因而可以不产生调用。

22、内联函数机制对于短函数而言是值得使用的,但对于在程序中多次被调用的长函数并不合适,因为在此情况下,是用内联函数时,函数代码会被复制到多个位置,从而会急剧增加可执行代码的长度。出于这一原因。C++允许编译器对于过长的函数忽略inline关键字。因此,inline关键字只是对编译器提出了一个要求,至于世界收还是忽略这一请求则有编译器来决定。

 

 

习题

5.1 使用函数的好处是什么?如何声明一个函数?如何调用一个函数?

灵活,易读,可扩展,易维护。

返回值类型 函数签名

函数名,参数,参数是可选的。

5.2主函数的返回类型是什么?

整形的数字

5.3 你恩能够用条件运算符简化程序清单5-1中的函数max嘛?

int getMax(int a,int b){

return a>b?a:b;

}

5.4下面叙述是正确的还是错误的?对一个返回类型为void的函数的调用只能作为语句使用,而对一个有返回值的函数的调用只能作为一个表达式的一部分。

错误的。前半句的说法是没有问题的,但是后半句的说法存在问题。同样也可以作为语句使用。

5.5在一个有返回值的函数中没有编写return 语句会造成什么错误?能在一个void函数中使用return语句,如下面程序那样吗?

void p(){

int i;

while(true){

//prompt the user to enter an integer

cout<< “Enter an integer:”;

cin>> i;

if(i==0)

return ;

cout<<” i is “<< i << endl;

}

}

编译都通不过啊!!!必须要写return的。

可以。

5.6解释属于:参数、自变量和 函数签名。

参数 分为两类,实际参数和形式参数。实际参数 是指,在函数调用过程中,调用处需要传入的数据,成为实际参数。形式参数是 被调用的函数中用来接收数据的参数,也称自变量。函数签名,是函数名个由形式参数构成的参数列表共同组成的。所谓的参数列表包括形式参数的个数,数据类型,以及形式参数的顺序。

5.7为下面的函数编写函数头:

给定销售额和佣金率,计算销售佣金。

double getCommission(double saleAmount,double commisionRate);

给定年份和月份,打印该月的日历。

void printCalendar(int year,int month);

计算一个数的*方根

double getRootOfANumber(double number);

检查一个数是否是偶数,若是返回true.

bool isEven(int number);

以指定次数打印一个字符。

void print(int time,char ch);

给定贷款额、贷款年限和年利率,计算每月还款额。

double getPaymentOfAMonth(double loan,double year,double annualRate);

给定一个小写字母,求对应的大写字母。

char getUpperCase(char ch);

5.8找出下面程序中的错误,并改正之。

int xFunction(int n)

{

cout<<n;

}

 

function1(int n,m)//m需要指定参数类型

{

n+=m;

xFunction(3.4);//没有可以调用的函数修改方式1是,把上面函数签名里的int改成double

}

5.9什么是按值方式?什么是按引用方式?给出下面程序的运行结果。

按值方式,就是在程序调用的过程中传递给形式参数的是实际参数的值,在函数体中对于形式参数的修改,并不会反馈到实际参数上。按引用方式是把实际参数的别名传递给形式参数,本质上参与运算的是实际参数,对形式参数的修改会反馈到实际参数上。所以这种方式也被称作按共享方式传值。常见的例子就是两数互换。如果采用按值方式话,是不会起到效果的,但是如果是按引用方式的话是有效果的。

A:

#include <iostream>

using namespace std;

void maxValue(int value,int value2 ,int max){

if(value1 > value2)

max = value1;

else

max = value2;

}

int main(){

int max = 0;

maxValue(1,2,max);

cout<< “max is “<<max<< endl;

 

return 0;

}

运行结果:

max is 0

B:

#include <iostream>

using namespace std;

void maxValue(int value1,int value2,int &max)

{

if(value1 > value2)

max = value1;

else

max = value2;

}

int main(){

int max = 0;

maxValue(1,2,max);

cout<< “max is “<<max <<endl;

 

return 0;

}

运行结果:

max is 2

 

C:

#include <iostream>

using namespace std;

void f(int i,int num){

for(int j=1;j<=i;j++){

cout<< num<< “ “;

num*=2;

}

cout <<endl;

}

int main(){

int i = 1;

while(i<=6){

f(i,2);

i++;

}

 

return 0;

}

2

2 4

2 4 6

2 4 6 8

2 4 6 8 10

2 4 6 8 10 12

 

D:

#include <iostream>

using namespace std;

void f(int &i,int num)

{

for(int j = 1 ; j <= i ; j++)

{

cout<< num << “ “;

num *= 2;

}

 

cout<<endl;

}

int main(){

int i = 1;

while(i<=6)

{

f(i,2);

i++;

}

 

return 0;

}

运行结果:

2

2 4

2 4 6

2 4 6 8

2 4 6 8 10

2 4 6 8 10 12

 

5.10 对于上一题中的程序a,分别给出函数max被调用前、刚刚进入max时,max返回之前以及max刚刚返回后的调用栈的内容。

调用前,没值

进入 1 2 0

返回前 1 2 2

刚刚返回 毛儿都没了。

5.11 给出下面程序的输出结果。

#include <iostream>

using namespace std;

voidf(double &p){

p+=2;

}

int main(){

double x = 10;

int y = 10;

f(x);

f(y);

 

cout<< “x is “<< x<< endl;

cout<< “y is “<< y << endl;

 

return 0;

}

编译通不过。

 

5.12 什么是函数重载?可以定义两个同名但参数类型不同的函数么?可以在一个程序中定义两个同名且参数相同,但返回值类型不同的函数吗?

具有相同函数名但是参数列表不同的函数组,通常完成的功能是相同的,只是在参数列表里面有差别。可以,不可以。

5.13 下面程序有什么错误?

void p(int i){

cout<< i <<endl;

}

int p(int j){

cout<< j << endl;

}

已经定义了一个p(int ) 函数。编译通不过了。

5.14 下面程序中有什么错误?

#include <iostream>

using namespace std;

void p(int &i){

cout << i <<endl;

}

int p(int j){

cout << j<< endl;

}

int main(){

int k = 5;

p(k);

 

return 0;

}

二义调用,这个时候调用哪个参数都是可以的,这样会出问题。

唉?忽然想到如果这个时候给调用加一个返回值 还会报错么?应该不会了吧。试试

他这样写迷惑性还不大:

我这样写迷惑性就更大了。

#include <iostream>

using namespace std;

void p(int &i){

cout << i << endl;

}

int p(int j){

cout << j << endl;

}

int main(){

int k = 5;

int c = p(k);//在这里依然通不过。

 

return 0;

}

 

5.15 下面哪些函数声明是非法的?

void t1(int x,int y =0,int z);//非法

void t2(int x = 0,int y =0,int z);//非法

void t3(int x,int y=0,int z = 0);

void t4(int x = 0,int y = 0,int z = 0);

 

5.16找出下面程序中的全局变量和局部变量。全局变量有默认值吗?局部变量呢?下面程序的输出结果是什么?

#include <iostream>

using namespace std;

 

int j;

int main(){

int i;

cout<< “ i is “<< i <<endl;

cout << “ j is “<< j << endl;

}

全局变量有默认值是0,局部变量没有默认值,下面程序的输出结果:

i is -858993460

j is 0

好吧 编译都通不过,但是某一次尝试 确实得到了这个 -858993460

 

5.17找出下面程序中的全局变量,局部变量和静态局部变量。程序的输出结果是什么?

#include <iostream>

using namespace std;

int j =40;//全局变量

void p(){

int i = 5;//局部变量

static int j = 5;//静态全局变量

i++;

j++;

cout << “i is “<< i << endl;

cout << “ j is “<< j<< endl;

}

 

int main(){

p();

p();

}

i is 6

j is 6

i is 6

j is 7

 

5.18 找出下面程序中的错误并改正。

void p(int i){

int i =5;//重名了,把 int去了吧。

 

cou << “ i is “ << i << endl;

 

}

5.19下面说法是正确的还是错误的?三角函数的参数表示弧度值。

对的

#include <iostream>

 

using namespace std;

int main(){

 

cout<<sin(3.141592 / 2);

system("pause");

return 0;

 

}

输出 1

5.20编写三个表达式分别生成:34~55之间的随机整数,0~999之间的随机整数;随机小写字母。

int get34To55(){

return 34+rand()%(55-34+1);

}

int get0To999(){

return rand()%1000;//0+rand()%(999-0+1)

}

char getRandomLowerCase(){

return static_cast<int>( ‘a’+rand()%(‘z’-’a’+1));

}

5.21 假设PI的值为3.14159E的值为2.71828.求下面函数的结果。

A.sqrt(4.0)   2.0

B.sin(2*PI)   0

C.cos(2*PI)   1

D.pow(2,2)   4

E.log(E)   1

F.exp(1.0)   2.71828

G.max(2,min(3,4)) 3

H.fmod(2.5,2.3)   0.2

I.ceil(-2.5)   -2

J.floor(-2.5)   -3

K.abs(-2.5f)   2.5

L.log10(100.0)   2

M.cos(PI)   -1

N.ceil(2.5)   3

O.floor(2.5)   2

P.pow(2.0,4)   16

Q.fmod(4.2,3.5)  0.7

R.Ceil(abs(-2.5))   3

 


程序设计练习

5.1将一个大写字母转换为小写字母

#include <iostream>

using namespace std;

 

char upperCast2LowerCase(char ch){

return static_cast<char>(ch +'a'-'A');

 

}

 

int main(){

 

cout << "thisaprogramabout" << endl;

 

cout<<upperCast2LowerCase('C');

 

system("pause");

return 0;

 

}

 

5.2计算一个整数的数字之和:

#include <iostream>

using namespace std;

 

//将一个整数中的所有数字相加 ,范围是0-1000

 

int getSurfaceSum(int number){

int sum = 0;

while (number>0){

sum += number % 10;

number /= 10;

}

return sum;

}

int main(){

int number = 0;

cout << "请输入一个(0-1000)的整数,计算它的每个数字之和" << endl;

cin >> number;

cout << "数字和为: " << getSurfaceSum(number) << endl;

 

system("pause");

 

return 0;

 

 

 

}

 

5.3编写一个函数逆序显示一个整数,函数头如下:

void reverse(int nuber)

例如,reverse(3456) 应显示6543.

#include <iostream>

using namespace std;

 

//将一个整数中的所有数字相加 ,范围是0-1000

 

void reverse(int number){

 

while (number > 0){

 

cout << number % 10;

number /= 10;

 

}

 

 

 

}

int main(){

int number = 0;

cout << "数字逆序显示,输入数字:" << endl;

cin >> number;

//cout << "逆序为: " << reverse(number) << endl;

 

reverse(number);

 

system("pause");

 

return 0;

 

 

 

}

5.4返回一个整数的逆序

int reverse(int number)

#include <iostream>

using namespace std;

 

//将一个整数中的所有数字相加 ,范围是0-1000

 

int getBits(int number){

 

if (number == 0)return 1;

int bit = 0;

while (number>0){

number /= 10;

bit++;

}

return bit;

}

 

int reverse(int number){

 

int sum = 0;

int bit = getBits(number);

int stage = pow(10,bit-1);

int currentNumber = 0;

while (number > 0){

 

currentNumber =  number % 10;

sum += currentNumber*stage;

stage /= 10;

number /= 10;

 

}

 

 

return sum;

 

 

 

}

int main(){

int number = 0;

cout << "数字逆序显示,输入数字:" << endl;

cin >> number;

cout << "逆序为: " << reverse(number) << endl;

//cout<<getBits(number);

 

//reverse(number);

 

system("pause");

 

return 0;

 

 

 

}

 

5.5 对三个整数进行排序:

void sort(double &num1,double &num2,double &num3)

#include <iostream>

using namespace std;

 

void swap(double &a, double &b){

double temp = a;

a = b;

b = temp;

}

 

 

void sort(double &num1, double &num2, double &num3){

if (num1>num2){

swap(num1, num2);

if (num3 < num1)

swap(num1, num3);

else if (num3 < num2)

swap(num2, num3);

}

else{

if (num3 < num1)

swap(num1, num3);

else if (num3 < num2)

swap(num2, num3);

}

 

}

 

int main(){

 

cout << "对三个数字排序" << endl;

double a1, a2, a3;

cout << "输入三个数字" << endl;

cin >> a1 >> a2 >> a3;

sort(a1, a2, a3);

cout << a1<<"  "<< a2<<"  "<< a3 << endl;

 

system("pause");

return 0;

 

}

 

5.6 输出图案:

 

 

#include <iostream>

#include <iomanip>

using namespace std;

 

void displayPattern(int n){

for (int i = 1; i <= n; i++){

for (int j = 0; j < n - i; j++)

cout << "   ";

for (int j = i; j>0;j--){

cout << setw(3)<<j ;

}

cout << endl;

}

 

}

 

int main(){

 

cout << "输出图案" << endl;

 

displayPattern(5);

 

system("pause");

return 0;

 

}

 

5.7计算投资的未来价值:

#include <iostream>

using namespace std;

double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, double years){//年利率转化成月利率

//输入的是一个 类似于3.25 的数值,/100 得到百分数形式的 /12 得到月利率。

//return pow(investmentAmount*(1 + interestRate / 1200), numberOfYears*12);

 

return investmentAmount*(pow(1 + monthlyInterestRate / 1200, years * 12));

}

 

void displayInvestmentTable(double investmentAmount, double monthlyInterestRate){

 

cout << "\t未来价值" << endl;

for (int i = 1; i <= 30; i++){

cout << i << "\t" << futureInvestmentValue(investmentAmount, monthlyInterestRate, i) << endl;;

}

 

 

 

}

 

 

int main(){

cout << "计算投资未来价值" << endl;

cout << "投资总额,比如1000" << endl;

double money = 0;

cin >> money;

cout << "年利率,比如3.25" << endl;

double rate = 0;

cin >> rate;

 

//cout << "未来价值: " << futureInvestmentValue(money, rate, year) << endl;

displayInvestmentTable(money,rate);

 

 

system("pause");

return 0;

 

 

 

}

 

练习5.8温度转换表

 

#include <iostream>

using namespace std;

double celsiusToFahrenheit(double celsius){

 

return celsius*9.0 / 5 + 32;

 

 

}

 

double fahrenheitToCelsius(double fahrenheit){

 

return (fahrenheit - 32) * 5 / 9;

}

 

void displayTemperatureTransformTable(){

 

double fahrenheit = 120;

cout << "Celsius\tFahrenheit\t|\tFahrenheit\tCelsius" << endl;

for (double celsius = 40; celsius > 30.5;celsius--,fahrenheit-=10){

cout << celsius << "\t" << celsiusToFahrenheit(celsius) << "\t\t|\t" << fahrenheit <<"\t\t"<< fahrenheitToCelsius(fahrenheit) << endl;

}

 

 

}

 

int main(){

cout << "温度转换表" << endl;

 

//cout << "未来价值: " << futureInvestmentValue(money, rate, year) << endl;

displayTemperatureTransformTable();

 

system("pause");

return 0;

 

 

 

}

 

练习5.9编写一个头文件,包含下面两个函数:

double footToMeter(double foot)

 

double meterToFoot(double meter)

转换公式

meter = 0.305*foot

main.cpp

#include <iostream>

#include "footAndMeter.h"

using namespace std;

void displayFootAndMeterTransformTable(){

cout << "Feet\tMeters\t|\tMeters\tFeet" << endl;

double meters = 20;

for (double feet = 1; feet < 10.5;feet++,meters+=5){

cout << feet << "\t" << footToMeter(feet) << "\t|\t" << meters << "\t" << meterToFoot(meters) << endl;

}

}

 

int main(){

cout << "英尺和米转换表" << endl;

displayFootAndMeterTransformTable();

 

system("pause");

return 0;

 

}

 

footAndMeter.h

double footToMeter(double foot){

 

return 0.305*foot;

}

 

double meterToFoot(double meter){

return meter / 0.305;

}

5.10 编写函数返回两个正整数的最大公约数,函数头如下:

int gcd(int m,int n)

 

#include <iostream>

 

int min(int a,int b){

if (a < b)

return a;

return b;

}

int gcd(int a,int b){

int grestestCommonDivisor = 1;

 

 

for (int i = min(a, b) / 2; i >1; i--){//有时候在想要抠这一次两次么?他们说抠了好。

//std::cout << i;

if (a%i == 0 && b%i == 0){

grestestCommonDivisor = i;

break;

}

}

return grestestCommonDivisor;

 

}

 

5.11 计算佣金

double computeCommission(double salesAmount)

 

 

#include <iostream>

using namespace std;

 

double computeCommission(double salesAmount){

 

if (salesAmount<5000){

return salesAmount*0.08;

}

else if (salesAmount<10000){

return 5000 * 0.08 + (salesAmount - 5000)*0.1;

}

else {

return 5000 * 0.08 + (10000 - 5000)*0.1 + (salesAmount - 10000)*0.12;

}

}

void displayCommissionTable(){

cout << "SalesAmount\tCommission" << endl;

for (int salesAmount = 10000; salesAmount <= 100000; salesAmount += 5000){

cout << salesAmount << "\t\t" << computeCommission(salesAmount) << endl;

}

}

 

int main(){

cout << "打印佣金表" << endl;

displayCommissionTable();

 

system("pause");

return 0;

 

}

 

512打印字符

void printChars(char ch1,char ch2,int numberPerLine)

参数 1 Z 10

 

#include <iostream>

using namespace std;

void printChars(char ch1, char ch2, int perLine){

int count = 0;

for (int i = ch1; i <= ch2; i++){

 

cout << static_cast<char>(i) << " ";

count++;

if ((count + 1) % perLine == 0)

cout << endl;

}

cout << endl;

 

}

 

int main(){

cout << "打印字符表" << endl;

printChars('1','z',10);

 

system("pause");

return 0;

 

}

 

5.13 求级数和

公式:

#include <iostream>

using namespace std;

double getSum(int number){

double sum = 0;

for (double i = 2; i <= number; i++){

 

sum += (i-1) / i;

 

}

return sum;

 

}

void displaySumTable(){

 

cout << "i\tm(i)" << endl;

for (int i = 2; i <= 20;i++){

cout << i << "\t" << getSum(i) << endl;

}

}

 

int main(){

 

cout << "计算级数和" << endl;

displaySumTable();

 

system("pause");

 

return 0;

}

 

5.14 计算级数

编写一个函数计算下面级数:

 

第四章就写过这个 PI

#include <iostream>

#include <iomanip>

using namespace std;

double getSumOfPI(int number){

 

double sum = 0;

for (int i = number * 2 + 1; i >= 1; i -= 4){

sum += 1.0 / i;

}

return sum;

 

}

 

double getMinusOfPI(int number){

 

double sum = 0;

for (int i = number * 2 - 1; i >= 3; i -= 4){

sum += 1.0 / i;

}

return sum;

 

}

 

 

//传递参数不会减小精度。

double getPI(int number){//由于知道,右边开始算比较精确,所以从右边开始计算:

 

return 4*(getSumOfPI(number) - getMinusOfPI(number));

}

 

 

int main(){

 

cout << "计算级数和" << endl;

cout << setw(20) << fixed << setprecision(20) << getPI(10000) << endl;

cout << setw(20) << fixed << setprecision(20) << getPI(20000) << endl;

cout << setw(20) << fixed << setprecision(20) << getPI(100000) << endl;

cout << setw(20) << fixed << setprecision(20) << getPI(1000000) << endl;

 

//getPI(20000);

//getPI(100000);

system("pause");

return 0;

 

}

 

5.15打印纳税表

 

#include <iostream>

#pragma warning(disable:4703)

using namespace std;

/* 计算税款,根据美国2002年的数据

说实话连人家的这些例子都觉得特别棒!!!

*/

 

int singleFilers[5] = { 6000, 27950, 67700, 141250, 307050 };

int marriedFileJointly[5] = { 12000, 46700, 112850, 171950, 307050 };

int marriedFileSeparately[5] = { 6000, 23350, 56425, 85975, 153525 };

int headOfHousehold[5] = { 10000, 37450, 96700, 15600, 307050 };

#define stageOne 10.0

#define stageTwo 15.0

#define stageThree 27.0

#define stageFour 30.0

#define stageFive 35.0

#define stageSix 38.6

double taxStageRate[6] = { stageOne / 100, stageTwo / 100, stageThree / 100, stageFour / 100, stageFive / 100, stageSix / 100 };

 

 

//double getTax(double money, int* moneyStage, double* taxRateStage){

//

// return 0;

//

//}

 

/*

根据这个人的状态和 挣到的钱,来决定纳税金额。

现在的想法就是是不是可以因为这一组数据很有规律,所以想做一个数组,来规范这样的话,只需要根据不同的状态,来分不同的税率阶段就可以了

*/

double getTax(int status, double money){

int* MoneyStage;

if (status == 0){

MoneyStage = singleFilers;

}

else if (status == 1){

MoneyStage = marriedFileJointly;

}

else if (status == 2){

MoneyStage = marriedFileSeparately;

}

else if (status == 3){

MoneyStage = headOfHousehold;

}

double tax = 0;

if (money <= MoneyStage[0]){

tax = (money - 0)*taxStageRate[0];//10

}

else if (money <= MoneyStage[1]){

 

tax = MoneyStage[0] * taxStageRate[0] + (money - MoneyStage[0]) * taxStageRate[1];//6000*10+(money-6000)*15

}

else if (money <= MoneyStage[2]){

tax = MoneyStage[0] * taxStageRate[0] + (MoneyStage[1] - MoneyStage[0]) * taxStageRate[1] + (money - MoneyStage[1])*taxStageRate[2];

}

else if (money <= MoneyStage[3]){

tax = MoneyStage[0] * taxStageRate[0] + (MoneyStage[1] - MoneyStage[0]) * taxStageRate[1] + (MoneyStage[2] - MoneyStage[1]) * taxStageRate[2] + (money - MoneyStage[2])*taxStageRate[3];

}

else if (money <= MoneyStage[4]){

tax = MoneyStage[0] * taxStageRate[0] + (MoneyStage[1] - MoneyStage[0]) * taxStageRate[1] + (MoneyStage[2] - MoneyStage[1]) * taxStageRate[2] + (MoneyStage[3] - MoneyStage[2]) * taxStageRate[3] + (money - MoneyStage[3])*taxStageRate[4];

}

else{

tax = MoneyStage[0] * taxStageRate[0] + (MoneyStage[1] - MoneyStage[0]) * taxStageRate[1] + (MoneyStage[2] - MoneyStage[1]) * taxStageRate[2] + (MoneyStage[3] - MoneyStage[2]) * taxStageRate[3] + (MoneyStage[4] - MoneyStage[3]) * taxStageRate[4] + (money - MoneyStage[4])*taxStageRate[5];

}

//tax = getTax(money,MoneyStage,taxStageRate);

 

return tax;

}

 

void displayTaxTable(){

 

cout << "可课税收入\t单身纳税者\t夫妻联合纳税者\t夫妻分别纳税者\t户主纳税者" << endl;

for (int i = 50000; i <= 60000; i += 50){

cout << i << "\t\t" << getTax(0, i) << "\t\t" << getTax(1, i) << "\t\t" << getTax(2, i) << "\t\t" << getTax(3, i) << endl;

}

}

 

int main(){

 

 

cout << "打印纳税表" << endl;

displayTaxTable();

system("pause");

return 0;

}

 

5.16 编写一个函数判断一个整数是否是素数

bool isPrime(int num)

找到1000个宿舍 每行十个。

 

#include <iostream>

#include <iomanip>

using namespace std;

bool isPrime(int number){

 

for (int i = 2; i <= number / 2; i++){

if (number%i == 0)

return false;

}

return true;

 

}

 

void displayPrimes(){

 

int count = 0;

for (int i = 2; count < 1000; i++){

 

if (isPrime(i)){

cout << setw(5) << i;

count++;

if ( count % 10 == 0)

cout << endl;

}

}

}

 

int main(){

 

 

cout << "打印1000个素数" << endl;

displayPrimes();

 

system("pause");

return 0;

 

}

 

5.17 生成矩阵

#include <iostream>

#include <ctime>

using namespace std;

 

int getRandom0To1(){

return rand() % 2;

}

 

void printMatrix(int n){

 

for (int i = 1; i <= n; i++){

for (int j = 1; j <= n; j++){

cout << getRandom0To1();

}

cout << endl;

}

}

 

int main(){

 

cout << "打印n阶矩阵,矩阵元素非01随机生成" << endl;

srand(time(0));

printMatrix(3);

 

system("pause");

return 0;

 

}

 

5.18 使用程序清单中的RandomCharacter 打印100个随机大写字母,100个 随机个位数字,每行打印10个字母或者数字。

 

#include <iostream>

#include <ctime>

#include "RandomChracter.h"

using namespace std;

 

void print100RandomUpperCase(){

 

for (int i = 0; i < 100; i++){

cout << getRandomUpperCase() << " ";

if ((i + 1) % 10 == 0)

cout << endl;

 

}

 

}

 

void print100RandomSingleNumber(){

 

for (int i = 0; i < 100; i++){

cout << getRandomNumber() << " ";

if ((i + 1) % 10 == 0)

cout << endl;

 

}

}

 

int main(){

srand(time(0));

 

print100RandomUpperCase();

cout << endl;

print100RandomSingleNumber();

 

system("pause");

return 0;

 

 

}

 

 

5.19 打印*方根表:

 

#include <iostream>

using namespace std;

 

void displaySquareRootTable(){

 

cout << "Number\tSquareRoot" << endl;

for (int i = 0; i <= 20;i+=2){

cout << i << "\t" << sqrt(i) << endl;

}

}

int main(){

 

displaySquareRootTable();

 

system("pause");

return 0;

 

}

 

5.20 三角形面积:

面积公式:

MyTriangle.h

#include <iostream>

bool isValid(double a, double b, double c){

if (a + b > c&&a + c > b&&b + c > a){

return true;

}

return false;

}

 

double area(double a, double b, double c){

double s = (a + b + c) / 2;

return sqrt(s*(s - a)*(s - b)*(s - c));

}

main.cpp

#include <iostream>

#include "MyTriangle.h"

using namespace std;

int main(){

 

cout << "计算三角形面积" << endl;

cout << "输入三角形三边" << endl;

double a, b, c;

cin >> a >> b >> c;

if (!isValid(a, b, c)){

cout << "三角形不合法" << endl;

}

else{

cout << "面积是:" << area(a, b, c) << endl;

}

system("pause");

return 0;

}

5.21 适用三角函数打印sin cos 表 角度 从 0°到360°,间隔为10°。结果舍入到小数点后四位。

#include <iostream>

#include <iomanip>

using namespace std;

#define PI 3.14159

void displaySinAndCosTable(){

cout << "Degree\tSin\tCos" << endl;

for (int i = 0; i <= 36; i += 1){

cout <<fixed<<setprecision(4)<< i*10 << "\t" << setw(5) << sin(i*PI /18) << "\t" << setw(5) << cos(i*PI /18) << endl;

}

}

int main(){

displaySinAndCosTable();

system("pause");

return 0;

}

 

5.22 随机生成10个数,计算*均数,和方差。

方差推到比较容易,应该可以在下一次展示出来的。

#include <iostream>

#include <ctime>

#include <iomanip>

using namespace std;

 

int getRandomNumber(){

return rand() % 1001;

}

 

double getAvg(double sum,int count){

return sum / count;

}

double getDeviation(double sumOfSquare,double squareOfSum,int count){//sumOfSquare *方和,squareOfSum 和的*方

//自己推了个公式。。。

 

 

return sqrt((sumOfSquare - squareOfSum / count)/count);

}

 

void getFinalResult(){

double mean = 0;

int sum = 0;

double sumOfSquare = 0;

//double squareOfSum = 0;

int currentNumber = 0;

for (int i = 0; i < 10; i++){

currentNumber =  getRandomNumber();

sumOfSquare += currentNumber*currentNumber;

sum += currentNumber;

cout << setw(4) << currentNumber;

if (i == 4)

cout << endl;

}

cout <<"*均数是: "<< getAvg(sum, 10) << endl;

cout << "方差是: " << getDeviation(sumOfSquare,sum*sum,10) << endl;

 

}

 

int main(){

 

srand(time(0));

//cout << getRandomSingleNumber();

getFinalResult();

//cout<<getDeviation(50, 144, 3);

 

system("pause");

 

return 0;

 

 

}

 

5.23 逼**方根。实现sqrt函数。

给了这样一个公式

nextGuesslastGuess*似相等的时候,认为nextGuess就是 这个数字的*方根了。

#include <iostream>

#include <iomanip>

using namespace std;

double mySqrt(double num){

 

double guess = 1;

double nextGuess = 0;

while (1){

nextGuess = (guess + num / guess) / 2;

if (abs(guess - nextGuess) < 0.0001)

return nextGuess;

guess = nextGuess;

 

}

 

}

int main(){

 

cout <<fixed<<setprecision(5)<< mySqrt(30) << endl;

 

system("pause");

return 0;

 

 

}

 

我也不知道 为啥,感觉挺简单的 想了这么久。。。

还差5个题。。。

 

5.24显示当前时间日期

#include <iostream>

#include <ctime>

#pragma warning(disable:4244)

 

using namespace std;

void showTime(void){

int totalSeconds = time(0);//得到从197011日到现在的秒数。

int currentSecond = totalSeconds % 60;//当前秒=总秒数%60.

int totalMinutes = totalSeconds / 60;//总分钟数 = 当前秒数/60

int currentMinute = totalMinutes % 60;//当前分钟数 = 总分钟数%60

int totalHours = totalMinutes / 60; //总分钟数/60= 当前小时数

int currentHour = (totalHours + 8) % 24;//这个结果几次出来都是2想到时区问题了,但是想的方式不对,没出结果,

//现在是早上10点,几次输出的都是2。百思不得解,这个返回的是0时区的时间,北京也就是现在呆的地方时东8区,应该+2,所以,得到结果了。

cout << currentHour << ":" << currentMinute << ":" << currentSecond << endl;

}

 

bool isLeapYear(int year){

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))

return true;

return false;

}

 

 

int getMonth(int year, int totaldays){

int currentMonth = 0;

int February = 28;

if (isLeapYear(year)){

February = 29;

}

 

if (totaldays > 31 * 6 + 30 * 4 + February){

currentMonth = 12;

}

else if (totaldays > 31 * 6 + 30 * 3 + February){

currentMonth = 11;

}

else if (totaldays > 31 * 5 + 30 * 3 + February){

currentMonth = 10;

}

else if (totaldays > 31 * 5 + 30 * 2 + February){

currentMonth = 9;

}

else if (totaldays > 31 * 4 + 30 * 2 + February){

currentMonth = 8;

}

else if (totaldays > 31 * 3 + 30 * 2 + February){

currentMonth = 7;

}

else if (totaldays > 31 * 3 + 30 * 1 + February){

currentMonth = 6;

}

else if (totaldays > 31 * 2 + 30 * 1 + February){

currentMonth = 5;

}

else if (totaldays > 31 * 2 + February){

currentMonth = 4;

}

else if (totaldays > 31 + February){

currentMonth = 3;

}

else if (totaldays > 31){

currentMonth = 2;

}

else

currentMonth = 1;

 

return currentMonth;

 

}

 

int getYear(int totalDays){

//cout << totalDays << endl;

const int unixEpoch = 1970;

int currentYear = unixEpoch;

//int currentMonth = 0;

//放在循环里面一直做这个

while (totalDays>=365){

 

if (totalDays > 365 * 400 + 24 * 4 + 1){

totalDays -= 365 * 400 + 24 * 4 + 1;

currentYear += 400;

}

else if (totalDays>365*100+25-1){

totalDays -= 365 * 100 + 25 - 1;

currentYear += 100;

}

else if (totalDays>365*4+1){

totalDays -= 365 * 4 + 1;

currentYear += 4;

}

else if (totalDays > 365){

if (isLeapYear(currentYear)){

totalDays -= 366;

}

else

totalDays -= 365;

currentYear++;

}

}

//cout << totalDays << endl;

 

int currentMonth = 0;

int February = 28;

if (isLeapYear(currentYear)){

February = 29;

}

 

if (totalDays > 31 * 6 + 30 * 4 + February){

totalDays -= 31 * 6 + 30 * 4 + February;

currentMonth = 12;

}

else if (totalDays > 31 * 6 + 30 * 3 + February){

totalDays -= 31 * 6 + 30 * 3 + February;

currentMonth = 11;

}

else if (totalDays > 31 * 5 + 30 * 3 + February){

totalDays -= 31 * 5 + 30 * 3 + February;

currentMonth = 10;

}

else if (totalDays > 31 * 5 + 30 * 2 + February){

totalDays -= 31 * 5 + 30 * 2 + February;

currentMonth = 9;

}

else if (totalDays > 31 * 4 + 30 * 2 + February){

totalDays -= 31 * 4 + 30 * 2 + February;

currentMonth = 8;

}

else if (totalDays > 31 * 3 + 30 * 2 + February){

totalDays -= 31 * 3 + 30 * 2 + February;

currentMonth = 7;

}

else if (totalDays > 31 * 3 + 30 * 1 + February){

totalDays -= 31 * 3 + 30 * 1 + February;

currentMonth = 6;

}

else if (totalDays > 31 * 2 + 30 * 1 + February){

totalDays -= 31 * 2 + 30 * 1 + February;

currentMonth = 5;

}

else if (totalDays > 31 * 2 + February){

totalDays -= 31 * 2 + February;

currentMonth = 4;

}

else if (totalDays > 31 + February){

totalDays -= 31 + February;

currentMonth = 3;

}

else if (totalDays > 31){

totalDays -= 31;

currentMonth = 2;

}

else{

currentMonth = 1;

}

cout << "今天是" << currentYear << "" << currentMonth << ""<<(totalDays+1)<<" ";//这个 多少号这里面一定有bug

 

return currentYear;

 

}

 

void showDate(void){

 

int totalseconds = time(0);

int totalDays = totalseconds / (60*60*24);

int currentYear = 0;

getYear(totalDays);

 

 

}

 

int main(){

 

cout << "显示当前时间" << endl;

showDate();

showTime();

 

 

system("pause");

return 0;

 

 

}

 

#include <iostream>

#include <ctime>

#pragma warning(disable:4244)

 

using namespace std;

void showTime(void){

int totalSeconds = time(0);//得到从197011日到现在的秒数。

int currentSecond = totalSeconds % 60;//当前秒=总秒数%60.

int totalMinutes = totalSeconds / 60;//总分钟数 = 当前秒数/60

int currentMinute = totalMinutes % 60;//当前分钟数 = 总分钟数%60

int totalHours = totalMinutes / 60; //总分钟数/60= 当前小时数

int currentHour = (totalHours + 8) % 24;//这个结果几次出来都是2想到时区问题了,但是想的方式不对,没出结果,

//现在是早上10点,几次输出的都是2。百思不得解,这个返回的是0时区的时间,北京也就是现在呆的地方时东8区,应该+2,所以,得到结果了。

cout << currentHour << ":" << currentMinute << ":" << currentSecond << endl;

}

 

bool isLeapYear(int year){

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))

return true;

return false;

}

 

 

int getMonth(int year, int totaldays){

int currentMonth = 0;

int February = 28;

if (isLeapYear(year)){

February = 29;

}

 

if (totaldays > 31 * 6 + 30 * 4 + February){

currentMonth = 12;

}

else if (totaldays > 31 * 6 + 30 * 3 + February){

currentMonth = 11;

}

else if (totaldays > 31 * 5 + 30 * 3 + February){

currentMonth = 10;

}

else if (totaldays > 31 * 5 + 30 * 2 + February){

currentMonth = 9;

}

else if (totaldays > 31 * 4 + 30 * 2 + February){

currentMonth = 8;

}

else if (totaldays > 31 * 3 + 30 * 2 + February){

currentMonth = 7;

}

else if (totaldays > 31 * 3 + 30 * 1 + February){

currentMonth = 6;

}

else if (totaldays > 31 * 2 + 30 * 1 + February){

currentMonth = 5;

}

else if (totaldays > 31 * 2 + February){

currentMonth = 4;

}

else if (totaldays > 31 + February){

currentMonth = 3;

}

else if (totaldays > 31){

currentMonth = 2;

}

else

currentMonth = 1;

 

return currentMonth;

 

}

 

int getYear(int totalDays){

//cout << totalDays << endl;

const int unixEpoch = 1970;

int currentYear = unixEpoch;

//int currentMonth = 0;

//放在循环里面一直做这个

while (totalDays>=365){

 

if (totalDays > 365 * 400 + 24 * 4 + 1){

totalDays -= 365 * 400 + 24 * 4 + 1;

currentYear += 400;

}

else if (totalDays>365*100+25-1){

totalDays -= 365 * 100 + 25 - 1;

currentYear += 100;

}

else if (totalDays>365*4+1){

totalDays -= 365 * 4 + 1;

currentYear += 4;

}

else if (totalDays > 365){

if (isLeapYear(currentYear)){

totalDays -= 366;

}

else

totalDays -= 365;

currentYear++;

}

}

//cout << totalDays << endl;

 

int currentMonth = 0;

int February = 28;

if (isLeapYear(currentYear)){

February = 29;

}

 

if (totalDays > 31 * 6 + 30 * 4 + February){

totalDays -= 31 * 6 + 30 * 4 + February;

currentMonth = 12;

}

else if (totalDays > 31 * 6 + 30 * 3 + February){

totalDays -= 31 * 6 + 30 * 3 + February;

currentMonth = 11;

}

else if (totalDays > 31 * 5 + 30 * 3 + February){

totalDays -= 31 * 5 + 30 * 3 + February;

currentMonth = 10;

}

else if (totalDays > 31 * 5 + 30 * 2 + February){

totalDays -= 31 * 5 + 30 * 2 + February;

currentMonth = 9;

}

else if (totalDays > 31 * 4 + 30 * 2 + February){

totalDays -= 31 * 4 + 30 * 2 + February;

currentMonth = 8;

}

else if (totalDays > 31 * 3 + 30 * 2 + February){

totalDays -= 31 * 3 + 30 * 2 + February;

currentMonth = 7;

}

else if (totalDays > 31 * 3 + 30 * 1 + February){

totalDays -= 31 * 3 + 30 * 1 + February;

currentMonth = 6;

}

else if (totalDays > 31 * 2 + 30 * 1 + February){

totalDays -= 31 * 2 + 30 * 1 + February;

currentMonth = 5;

}

else if (totalDays > 31 * 2 + February){

totalDays -= 31 * 2 + February;

currentMonth = 4;

}

else if (totalDays > 31 + February){

totalDays -= 31 + February;

currentMonth = 3;

}

else if (totalDays > 31){

totalDays -= 31;

currentMonth = 2;

}

else{

currentMonth = 1;

}

cout << "今天是" << currentYear << "" << currentMonth << ""<<(totalDays+1)<<" ";//这个 多少号这里面一定有bug

 

return currentYear;

 

}

 

void showDate(void){

 

int totalseconds = time(0);

int totalDays = totalseconds / (60*60*24);

int currentYear = 0;

getYear(totalDays);

 

 

}

 

int main(){

 

cout << "显示当前时间" << endl;

showDate();

showTime();

 

 

system("pause");

return 0;

 

 

}

 

这个 还是比较难搞的,并且觉得,好像也未必能跑呢。

5.25逆序素数:

#include <iostream>

#include <iomanip>

using namespace std;

 

int getBits(int number){

 

if (number == 0)return 1;

int bit = 0;

while (number>0){

number /= 10;

bit++;

}

return bit;

}

 

int reverse(int number){

int sum = 0;

int bit = getBits(number);

int stage = pow(10, bit - 1);

int currentNumber = 0;

while (number > 0){

currentNumber = number % 10;

sum += currentNumber*stage;

stage /= 10;

number /= 10;

}

return sum;

}

 

bool isPrime(int number){

 

for (int i = 2; i <= number / 2; i++){

if (number%i == 0)

return false;

}

return true;

 

}

bool isEmirp(int number){

if (isPrime(number) && isPrime(reverse(number))){

return true;

}

return false;

 

 

}

 

void printEmirp(void){//prime  逆序变成 emirp 比如 13是 素数,逆序后的31 也是,这就是 逆序,2 3 5 也是 11 也是

 

int count = 0;

for (int i = 2; count < 100; i++){

 

if (isEmirp(i)){

cout << setw(5) << i;

count++;

if (count  % 10 == 0)

cout << endl;

}

 

 

 

}

 

 

}

int main(){

 

cout << "输出逆序素数" << endl;

printEmirp();

 

system("pause");

return 0;

 

}

 

5.26回文素数

#include <iostream>

#include <iomanip>

 

using namespace std;

 

bool isPrime(int number){

for (int i = 2; i <= number / 2; i++){

if (number%i == 0)

return false;

}

return true;

}

 

int getBits(int number){

 

if (number == 0)return 1;

int bit = 0;

while (number>0){

number /= 10;

bit++;

}

return bit;

}

 

int reverse(int number){

int sum = 0;

int bit = getBits(number);

int stage = pow(10, bit - 1);

int currentNumber = 0;

while (number > 0){

currentNumber = number % 10;

sum += currentNumber*stage;

stage /= 10;

number /= 10;

}

return sum;

}

 

bool isReverseSame(int number){

if (number == reverse(number))

return true;

return false;

}

 

bool isReverseSamePrime(int number){

if (isPrime(number) && isReverseSame(number))

return true;

return false;

 

}

 

void printReverseSamePrime(void){

 

int count = 0;

for (int i = 2; count < 100; i++){

 

if (isReverseSamePrime(i)){

cout << setw(7) << i;

count++;

if (count % 10 == 0)

cout << endl;

}

}

}

 

 

int main(){

 

cout << "输出回文素数" << endl;

printReverseSamePrime();

 

system("pause");

return 0;

 

}

 

5.27 梅森素数

#include <iostream>

#include <iomanip>

 

using namespace std;

 

bool isPrime(int number){

 

for (int i = 2; i <= number / 2; i++){

if (number%i == 0)

return false;

}

return true;

 

}

void printMersennePrime(){

int p=31;

cout << "p\t2^p-1" << endl;

int mersenne = 0;

for (int p = 2; p<=31; p++){

mersenne = pow(2, p) - 1;

if (isPrime(mersenne)){

cout << p << "\t" << mersenne << endl;

}

}

 

}

int main(){

 

cout << "输出梅森素数" << endl;

printMersennePrime();

 

system("pause");

return 0;

}

 

5.28 孪生素数

#include <iostream>

 

using namespace std;

 

bool isPrime(int number){

for (int i = 2; i <= number / 2; i++){

if (number%i == 0)

return false;

}

return true;

}

 

bool isTwinPrimes(int number){

 

if (isPrime(number) && isPrime(number + 2))

return true;

return false;

 

}

 

 

void printTwinPrimes(void){

 

for (int i = 2; i < 1000; i++){

 

if (isTwinPrimes(i)){

cout << "(" << i << "," << i + 2 << ")" << endl;

}

}

 

 

 

}

int main(){

cout << "输出孪生素数" << endl;

printTwinPrimes();

 

system("pause");

return 0;

 

 

}

 

posted on 2016-04-17 22:01  木鸟飞  阅读(1553)  评论(1编辑  收藏  举报

导航