【C++】入门训练

学习的是英文版的C++Primer,语言上有一点障碍,但是还可以接受。

今天跟大家分享我在学习初期掌握的一些基本的语句。

 

1.基本的乘法运算

    #include <iostream>
    int main ()
    {
    	int a, b;
    	std::cout << "Please type into two values." << std::endl;
    	std::cin >> a >> b;
    	std::cout << "The multiplication of " << a << " and " << b << " is " << a*b << " .";
    	return 0;
    }

 

这是一个基本的乘法运算,为了便于查看,我在结果上加入了一些说明文字。处于对编程规范的考虑,我希望我以后都能保持这个编写习惯哈。

2.a 到 b 的累加之和

这是一个很经典的题目,我在学习的时候刚好基础到了while和for的循环语句,于是我用while和for分别编写了程序。

首先,我们从简单的开始,1到10的累加之和。

——————————————————for循环————————————————————

    #include <iostream>

    int main()
    {  
    	int sum=0;
    	for (int a=1; a<=10; ++a)
    	sum+=a;
    	std::cout << "The inclusive from 1 to 10 is "<< sum<< " ."<< std::endl;
    	return 0;
    }

——————————————————while循环————————————————————

    #include <iostream>
    
    int main()
    {
    	int sum=0, a=1;
    	// keep executing the while untill "a" is greater than 10.
    	while (a<=10) {
    		sum+=a; //assign sum + a to sum,means sum=sum+a.
    		++a; //add 1 to a, means a=a+1.
    	}
   	std::cout << "Sum of 1 to 10 inclusive is " << sum << "." << std::endl;
    	return 0;
    }

我给while循环的程序加了注解,因为我一开始学习的时候并不是很熟悉这些语句。我想在旁边加上注解的话,复习起来应该会方便些。可以看出while循环的语句很明了,但是在写的时候也就相对要繁琐些,不过只要熟悉了方法,我想每个语句都有自己的优势。

1到10的就是这个样子,那么a到b的是不是跟这个差不多呢?

我们先看下while语句写的a到b的累加之和

    #include <iostream>

    int main () 
    {
    	int sum=0, a, b, c; //int "sum" to assign "a" into this inclusive.
    	std::cout << "Please type two values." << std::endl;
    	std::cin >> a >> b;
    	c=a; // copy the "a" inserted by user to c. 
    	while (a<=b)
        {
        	sum+=a; // sum=sum+a
        	++a; // a=a+1
        }
    	std::cout << "The inclusive from " << c << " to " << b << " is "<< sum << " ."<< std::endl; // "c" considered as the "a" inserted by user.
    	return 0;
    }

可以看到,这里加入了一个c去保留a的初始值,这样就可以在结果中显示一个完整的计算内容。For循环其实就更简单了,这边就不累述。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值