c++ primer 学习笔记-第一章


习题1-11:

int main(){
	std::cout << "input two numbers & print all of integers between them(smaller first):" << std::endl;
	int begin = 0, stop = 0;
	std::cin >> begin >> stop;
	while (begin <= stop)
	{
		std::cout << begin++ << " ";
	}
	std::cout << std::endl;
	getchar();
	getchar(); 
	return 0;
}

 在github上的答案,使用了std::swap对输入的两数大小关系进行调整,并使用for实现显示。 
  

对于swap功能,还可利用位运算实现,代码如下:

#include 
int main()
{ 
	std::cout << "input two numbers & print all of integers between them(smaller first):" << std::endl; 
	int begin = 0, stop = 0; 
	std::cin >> begin >> stop; 
	if (begin > stop)
	{
		begin ^= stop; stop ^= begin; 
		begin ^= stop; 
	}
	while (begin <= stop)
	{
		std::cout << begin++ << " "; 
	}
	std::cout << std::endl; getchar(); getchar(); 
	return 0;
}


 
  

 
  

习题1-17:

#include 

int main(){
	std::cout << "count how many times does a number occur consistently:" << std::endl;
	int val = 0, currVal = 0;
	if (std::cin >> currVal)
	{
		int cnt = 1;
		while (std::cin >> val)
		{
			if (currVal == val)
			{
				++cnt;
			}
			else
			{
				std::cout << "current value " << currVal << " occurs " << cnt << " times." << std::endl;
				cnt = 1;
				currVal = val;
			}
		}
		std::cout << "current value " << currVal << " occurs " << cnt << " times." << std::endl;
	}
	getchar();
	getchar();
	return 0;
}


习题1-23:

#include 
#include "Sales_item.h"
int main(){
	std::cout << "input several sale records & print:" << std::endl;
	Sales_item item, curItem;
	if (std::cin >> curItem)
	{
		int cnt = 1;
		while (std::cin >> item)
		{
			if (curItem.isbn() == item.isbn())
			{
				++cnt;
			}
			else
			{
				std::cout << "ISBN:" << curItem.isbn() << "  Sale number:" << cnt << std::endl;
				cnt = 1;
				curItem = item;
			}
		}
		std::cout << "ISBN:" << curItem.isbn() << "  Sale number:" << cnt << std::endl;
	}
	getchar();
	getchar();
	return 0;
}



你可能感兴趣的:(c++)