当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++项目:小试循环问题解答

C++项目:小试循环问题解答

2018年04月25日  | 移动技术网IT编程  | 我要评论

cosq-020,苍生赋,dj总统

【项目-小试循环】

  写出实现下面求解任务的程序【提示:m是一个变量,在程序中输入】
  (1)求1到m的平方和
  (2)求1到m间所有奇数的和
  (3)求1到m的倒数和,即1+12+13+14+...+1m

 


  (4)求值:1?12+13?14+...+(?1)(m+1)×1m

 


  (5)求m!,即1×2×3×...×m

 

 


【参考解答】

  写出实现下面求解任务的程序【提示:m是一个变量,在程序中输入】
  (1)求1到m的平方和

#include 
using namespace std;
int main( )
{
    int n,m,total;
    cin>>m;
    n=1;
    total=0;
    while(n<=m)
    {
        total+=(n*n);
        n++;
    }
    cout<<"total="<
<>

或用for循环:

#include 
using namespace std;
int main( )
{
    int n,m,total;
    cin>>m;
    total=0;
    for(n=1;n<=m;n++)
    {
        total+=(n*n);
    }
    cout<<"total="<
<>

  (2)求1到m间所有奇数的和

#include 
using namespace std;
int main( )
{
    int n,m,total;
    cin>>m;
    n=1;
    total=0;
    while(n<=m)
    {
        total+=n;
        n+=2;
    }
    cout<<"total="<
<>

或用for循环:

#include 
using namespace std;
int main( )
{
    int n,m,total;
    cin>>m;
    total=0;
    for(n=1;n<=m;n+=2)
    {
        total+=n;
    }
    cout<<"total="<
<>

  (3)求1到m的倒数和,即1+12+13+14+...+1m

 

 

#include 
using namespace std;
int main( )
{
    int n,m;
    double total;
    cin>>m;
    n=1;
    total=0;
    while(n<=m)
    {
        total+=(1.0/n); //注意1.0引发的类型转换,非常重要!
        n++;
    }
    cout<<"total="<
<>

或用for循环:

#include 
using namespace std;
int main( )
{
    int n,m;
    double total;
    cin>>m;
    n=1;
    total=0;
    for(n=1;n<=m;n++)
    {
        total+=(1.0/n); //注意1.0引发的类型转换,非常重要!
    }
    cout<<"total="<
<>

  (4)求值:1?12+13?14+...+(?1)(m+1)×1m

 

 

#include 
using namespace std;
int main( )
{
    int n,m,sign;
    double total;
    cin>>m;
    n=1;
    total=0;
    sign=1; //用sign代表累加项的符号,这是处理一正一负累加的技巧
    while(n<=m)
    {
        total+=(sign*(1.0/n)); 
        n++;
        sign*=-1; //sign变号
    }
    cout<<"total="<
<>

或用for循环:

#include 
using namespace std;
int main( )
{
    int n,m,sign;
    double total;
    cin>>m;
    n=1;
    sign=1; //用sign代表累加项的符号,这是处理一正一负累加的技巧
    total=0;
    for(n=1; n<=m; n++)
    {
        total+=(sign*(1.0/n)); //注意1.0引发的类型转换,非常重要!
        sign*=-1; //sign变号
    }
    cout<<"total="<
<>

  (5)求m!,即1×2×3×...×m

 

 

#include 
using namespace std;
int main( )
{
    int n,m;
    long fact; //阶乘值很大,数据类型方面考虑一些
    cin>>m;
    n=1;
    fact=1;
    while(n<=m)
    {
        fact*=n;
        n++;
    }
    cout<#include 
using namespace std;
int main( )
{
    int n,m;
    long fact; //阶乘值很大,数据类型方面考虑一些
    cin>>m;
    fact=1;
    for(n=1;n<=m;n++)
    {
        fact*=n;
    }
    cout<

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网