【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循環其實就更簡單了,這邊就不累述。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章