第四周作业

来源:互联网 发布:c语言中的库函数system 编辑:程序博客网 时间:2024/05/16 08:04

1.完成课本每一个编程题。要求先画出流程算法图或N-S图,然后编程实现,有可能的话使用两种以上方法;

2.编程求“百钱百鸡”问题。(鸡翁一值钱五,鸡母 一值钱三,鸡雏三值钱一。百钱买百鸡,问鸡翁、鸡母、鸡雏各几何?)

3.编程输入一个整数,计算它是几位数字,分别输出每一位数字,并输出各个数位上数字之和。

Part 1 在编程过程中出现了很多的错误,(1)在用科学计数法e表示时,e后面的数字不管是正的还是负的都不用加括号;(2)数字与变量相乘不能忘记乘号"*"。

#include<iostream>using namespace std;int main(){long double e=1.0;long double f=1.0;int i=1;for(i=1; (1.0/f)>=1e-6;i++){f*=i;                  //等价于f=f*ie+=1/f;                //等价于e=e+1/f}cout<<"e的近似值为: "<<e<<endl;return 0;   }


#include<iostream>#include<cmath>using namespace std;int main(){     long double pi=0.0; int n=1; for(n=1;1.0/(2*n-1)>=1e-6;n++) pi+=pow(-1,n-1)*1.0/(2*n-1);                  //调用指数函数pow cout<<"圆周率pi的近似值为:"<<4*pi<<endl; return 0;
#include <iostream>using namespace std;int main(){long double pi=1.0;double flag=-1.0;for(int i=3;1.0/i>=1e-6;i+=2){pi+=flag/i;    flag=-flag;}    cout<<"圆周率pi的近似值为: "<<4*pi<<endl;return 0;}



#include<iostream>using namespace std;int main(){int n=1,  p=1;for(n=2;;){p+=n*n;if(p<=1000)n++;else break;}p-=n*n;cout<<"p= "<<p<<endl;cout<<"输出n-1的值为: "<<n-1<<endl;return 0;}


#include<iostream>#include<iomanip>using namespace std;int main(){cout<<setw(7)<<"*"<<endl    <<setw(5)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<endl<<setw(3)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<endl<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<endl        <<setw(3)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<endl        <<setw(5)<<"*"<<setw(2)<<"*"<<setw(2)<<"*"<<endl<<setw(7)<<"*"<<endl;return 0;}


#include <iostream>using namespace std;int main(){    int n;cout<<"请输入一个数:"<<endl;cin>>n;if(n<=10)cout<<n<<"is"<<"0 to 10"<<endl;else if(n<=100)cout<<n<<"is"<<"10 to 100"<<endl;else if(n<=1000)        cout<<n<<"is"<<"100 to 1000"<<endl;else cout<<n<<"more then 1000"<<endl;return 0;}


Part 2这个程序写了很多次都失败了,看了同学写的,结果自己写的时候还是没写正确,严重打击吖,后来发现我是把同学的三个for语句写成一个了,究其原因,首先是自己对题目分析不够,还有就是对for语句没有理解透彻,特别是嵌套的for语句,后来通过看书,上网,比较清楚的知道了多个for的是怎样运行的,嘿嘿,最后终于写出来了。感觉过程好艰辛呐!

#include<iostream>using namespace std;int main(){int a, b, c, p, q;for(a=0;a<=20;a++)        //因为百元所以a<=20{for(b=0;b<=33;b++)    {for(c=0;c<=100;c+=3)  //因为只买百鸡,所以c最大值为100{p=a+b+c;q=5*a+3*b+c/3;if(p==100 && q==100)       //目的是满足百元百只的条件{cout<<"鸡翁为:"<<a<<"只"<<endl                <<"鸡母为:"<<b<<"只"<<endl<<"鸡雏为:"<<c<<"只"<<endl;cout<<"             "<<endl;}}                }}return 0;}


Part 3  

#include<iostream>using namespace std;int main(){int i=0, k=0, num, sum=0;cout<<"输入一个整数:"<<endl;cin>>num;while(num!=0){k=num%10;         //取余获得num的最小那一位的数字sum+=k;cout<<k;i++;num /=10;        //除去最低位的数字      }cout<<"该整数是: "<<i<<"位数字"<<endl;    cout<<"该整数各个数位上数字之和:"<<sum<<endl;return 0;}


后面还没做完啊,下次再补上了!


0 0