C++ Primer:Exercises Section 1.4.3

Exercise 1.14:如果輸入值相等,本節展示的程序將產生什麼問題?

#include <iostream>
int main()
{
	std::cout << "Enter two numbers:" << std::endl;
	int v1, v2;
	std::cin >> v1 >> v2; // read input
	// use smaller number as lower bound for summation
	// and larger number as upper bound
	int lower, upper;
	if (v1 <= v2) {
		lower = v1;
		upper = v2;
	} else {
		lower = v2;
		upper = v1;
	}
	int sum = 0;
	// sum values from lower up to and including upper
	for (int val = lower; val <= upper; ++val)
		sum += val; // sum = sum + val

	std::cout << "Sum of " << lower
		<< " to " << upper
		<< " inclusive is "
		<< sum << std::endl;
	return 0;
}


僅計算一次輸入值,未求和

Exercise 1.15:用兩個相等的值作爲輸入編譯並運行本節中的程序。將實際輸出與你在上一習題中所做的預測相比較,解釋實際結果和你預計的結果間的不相符之處。

僅計算一次輸入值,未求和

Exercise 1.16:編寫程序,輸出用戶輸入的兩個數中的較大者。

#include <iostream>
int main()
{
	std::cout << "Enter two numbers:" << std::endl;
	int v1, v2;
	std::cin >> v1 >> v2; // read input
	if (v1 < v2) {
		std::cout<<v2;
	} else if(v1>v2) {
		std::cout<<v1;
	}else{std::cout<<"Two number are equal.";}
	return 0;
}

Exercise 1.17:編寫程序,要求用戶輸入一組數。輸出信息說明其中有多少個負數

#include <iostream>
int main()
{
	std::cout << "Enter two numbers:" << std::endl;
	int v1, v2,cout;
	cout = 0;
	std::cin >> v1 >> v2; // read input
	if (v1 < 0) {
		++cout;
	} else if(v2 < 0) {
		++cout;
	}
	std::cout<<cout;
	return 0;
}



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