第4章节-课后习题评讲.pptVIP

  • 5
  • 0
  • 约3.17千字
  • 约 13页
  • 2017-09-14 发布于浙江
  • 举报
第4章节-课后习题评讲

4,编写函数,求两个整数的最大公约数和最小公倍数。 方法1:直接循环的思想 4,编写函数,求两个整数的最大公约数和最小公倍数。 方法2:辗转相除法 6:编写程序,要求输人四位数的年份、两位数的月份和日期,把它们按“年 月 日”的格式输出,并计算它是这一年的第几天。 6:编写程序,要求输人四位数的年份、两位数的月份和日期,把它们按“年 月 日”的格式输出,并计算它是这一年的第几天。 今日内容 0,分别用迭代法和递归函数来求Fibonacci数列第20项。 1,写一个程序,找出给定数组中具有最小值的元素及其下标。 2,定义一个函数,其的功能是:在第一个循环中给前10个数组元素依次赋值1、2、3、4、5、6、7、8、9、10;在第二个循环中使a数组前10个元素中的值对称折叠,变成1、2、3、4、5、5、4、3、2、1。 3,书上146页第1题 高级程序设计C++ 温蜜 第4章 C++函数 温蜜 wenmi2222@163.com 上海电力学院计信学院 本章主要内容 1.编写函数,定义两个unsigned short int型的参数,返回两个参数的商,其数据类型为short int。如果第二个参数为0,输出错误提示信息。 2. 3. 4.编写函数,求两个整数的最大公约数和最小公倍数。 5.编写递归函数,计算x的y(y0)次幂。 6.编写程序,要求输人四位数的年份、两位数的月份和日期,把它们按“年 月 日”的格式输出,并计算它是这一年的第几天。 1.编写函数,定义两个unsigned short int型的参数,返 回两个参数的商,其数据类型为short int。如果第二个参 数为0,输出错误提示信息。 short int Divd (unsigned short int a, unsigned short int b) { if (b == 0) return -1; else return a/b; } 1.(con.) #includeiostream using namespace std; void main() { unsigned short int x, y; short int z; cout Enter 2 numbers:; cin xy; z = Divd(x, y); if (z-1) cout Answer: z; else cout Error, cant divide by zero!; return 0; } int maxp(int x, int y) { int i; int t=(xy?x:y); //找2者中最小数 for(i=t; ;i--) { if(x%i==0 y%i==0) break; } return i; } 常见错: if(x%i==0y%i==0) return i; else return 0; int maxp(int x, int y) { int t ; if (i j) { t= i; i = j; j = t; } while(j != 0) { t= i % j; i = j; j = t; } return i; } 4 con. 最小公倍数方法1: #include iostream using namespace std; int main( ) { int a,b,x,y; cout 请输入一个整数:; cin a; cout 请输入另一个整数:; cin b ; x = maxp(a,b); y = i * j / x; cout a 和 b 的最大公约数是: x endl; cout a 和 b 的最小公倍数是: y endl; } 4 con. 最小公倍数方法2: #include iostream using namespace std; int main( ) { int a,b,x,y; cout 请输入一个整数:; cin a; cout 请输入另一个整数:; cin b ; x = maxp(a,b); y = minb(a,b); cout a 和 b 的最大公约数是: x endl; cout a 和 b 的最小公倍数是: y endl; } int minb(int x, int y) { int i; int t=(xy?x:y); //找2者中最大数 for(i=t; ;i++)

文档评论(0)

1亿VIP精品文档

相关文档