C++课后题(1)

使用级数计算圆周率

m(i)=4\left ( \left 1-1/3+1/5-1/7.....)\right )

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

float m(int); 
int main(int argc, char *argv[])
{
	cout << "i" << "      " << "m(i)" << endl;
    //cout << m(10) << endl;
    for(int j=1; j<10000; j++)
    {
    	cout <<setw(5) << j << "     " << setw(15) << m(j) << endl;
    }
	return 0;
}

float m(int n)
{
	float sum = 0;
	for(int i=1; i<=n; i++)
	{
		sum += pow(-1.0, i+1)*1.0/(2*i-1);
	}
	return 4.0*sum;
}

寻找孪生素数:

素数a, 素数b,  若b-a=2, 则a,b为孪生素数

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

bool isPrime(int);
//bool isTwinPrime(int);

int main(int argc, char *argv[])
{
    for(int j=2; j<=1000; j++)
    {
    	if(isPrime(j) && isPrime(j+2))
    	{
	    	cout << "(" << j << " , " << j+2 << ")" << endl;
	    }
    }
	return 0;
}

bool isPrime(int n)
{
   bool prime = true;
   for(int i=2; i<n; i++)
   {
   	  if(n%i==0)
   	  {
  	     prime = false;
	     break; 	
      }
   }
   return prime;
}


寻找回文素数:

判断一个数是否为回文数,有多种方法,常见的有三种:

1.将输入数字转化为字符串。回文数关于中心对称,只需比较对称的数是否相等即可。

2.采用除10取余的方法,从最低位开始,依次取出该数的各位数字,然后用最低为充当最高位,按反序构成新的数,再与原数比较。

3.采用栈的方式。判断出栈的元素与栈内字符是否相等。

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

bool isPrime(int);
bool isPalindromicPrime(int);
bool isPalindromic(int n);
//bool isTwinPrime(int);

int main(int argc, char *argv[])
{
    //cout << isPalindromic(100097) << endl;
    int count = 0;
    int k = 2;
	while(count<100)
	{
		if(isPalindromicPrime(k))
		{
		    count++;
			cout << setw(5) << k << endl;
			//if(count%10==0)  cout << endl;	
		}
		k++;
	}    
	return 0;
}

bool isPrime(int n)
{
   bool prime = true;
   for(int i=2; i<n; i++)
   {
   	  if(n%i==0)
   	  {
  	     prime = false;
	     break; 	
      }
   }
   return prime;
}

bool isPalindromic(int n)
{
	unsigned int i=n;
	unsigned int m=0;
	while(i>0)
	{
		m = m*10 + i%10;
		i = i / 10;
	}
	return m==n;
}


bool isPalindromicPrime(int n)
{
   bool PalindromicPrime = false;
   if(isPrime(n))
   {
   	   if(isPalindromic(n))
   	   {
           PalindromicPrime = true;
   	   }
   }
   return PalindromicPrime; 
}



6. 巴比伦方法实现sqrt()函数

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstdlib>
#include <time.h>

using namespace std;

double cal_sqrt(int );
int main(int argc, char *argv[])
{
    cout << "Enter a number: ";
    int nn;
    cin >> nn;
    double result = cal_sqrt(nn);
    cout << "sqrt(" << nn << ")" << " is " << result << endl;
	return 0;
}

double cal_sqrt(int n)  // 巴比伦方法实现开跟运算 
{
	srand(time(0));
	//double last_guess = static_cast<double>(rand() % 10);  // generate random number[0, 10)
	double last_guess = 1.0;
	double next_guess = (last_guess + (n / last_guess)) / 2.0;
	int count = 0;
	cout << "Iteration" << "       " << "sqrt" << endl;
	while(abs(last_guess - next_guess) > 0.000001)
	{
                last_guess = next_guess;
		next_guess = (last_guess + (n / last_guess)) / 2.0;
		count++; 
		cout << count << "            " << next_guess << endl;		
	} 
	return next_guess;
}


利用级数来逼近e

e = 1 + 1/1! + 1/2! + 1/3! + .......+ 1/i!

#include <iostream>
#include <cmath> 
#include <iomanip>

using namespace std;

int jiecheng(int);
double calculate_e(int);

int main(int argc, char *argv[])
{
    cout << calculate_e(20) << endl;
    return 0;
}


double calculate_e(int n)
{
	double sum = 0.0;
	for(int k=0; k<=n; k++)
	{
		sum += 1.0 / jiecheng(k);
	}
	return sum;
}


int jiecheng(int n)
{
	int a = 1;
	if(n==0)
	{
		return a;
	}
	else
	{
	    for(int i=n; i>0; i--)
     	{
		   a = a*i;
	    }
    	return a;
 	}

}

实现简单的计算器:

#include <iostream>
#include <cmath> 
#include <iomanip>
#include <cstdlib>
#include <time.h>

using namespace std;

void display_menu();

int main(int argc, char *argv[])
{
	while(true)
	{
		srand(time(0));
	        display_menu();
		int answer; 
		cout << "Please Enter Your Choice: ";
		cin >> answer;
		float x1, x2;
	        x1 = rand() % 10;  // Generate the first random number
		x2 = rand() % 10;  // The second
		if(answer==1)
		{
			cout << "What is " << x1 << " + " << x2 << " ? " << endl;
			cout << "Your answer: ";
			float tmp;
			cin >> tmp;
			if(tmp==(x1+x2))
			{
				cout << "You are correct!" << endl;
			}
			else
			{
				cout << "YUou are wrong!" << endl;
			}
		}
		if(answer==2)
		{
			cout << "What is " << x1 << " - " << x2 << " ? " << endl;
			cout << "Your answer: ";
			float tmp;
	 	    cin >> tmp;
	 	    if(tmp==(x1-x2))
			{
				cout << "You are correct!" << endl;
			}
			else
			{
				cout << "YUou are wrong!" << endl;
			}
		}
		if(answer==3)
		{
			cout << "What is " << x1 << " x " << x2 << " ? " << endl;
			cout << "Your answer: ";
			float tmp;
	 	    cin >> tmp;
	 	    if(tmp==(x1*x2))
			{
				cout << "You are correct!" << endl;
			}
			else
			{
				cout << "YUou are wrong!" << endl;
			}
		}
		if(answer==4)
		{
			while(x2==0)
			{
				x2 = rand() % 10;
			}
			cout << "What is " << x1 << " / " << x2 << " ? " << endl;
			cout << "Your answer: ";
			float tmp;
	 	    cin >> tmp;
	 	    if(tmp==(x1/x2))
			{
				cout << "You are correct!" << endl;
			}
			else
			{
				cout << "YUou are wrong!" << endl;
			}
		}
		
		if(answer==5)
		{
		   exit(0);
		}
	}
	
	return 0;
}

void display_menu()
{
	cout << "   Main  menu   " << endl;
	cout << "   1. Addition  " << endl;
	cout << "   2. Substraction   " << endl;
	cout << "   3. Multiply   " << endl;
	cout << "   4. Division   " << endl;
	cout << "   5. Exit    " << endl;
}



密码有效性检验:
假定密码的规则为:

1.密码至少有八个字符

2.密码必须仅包含字母和数字

3.密码必须包含至少两个数字

code:

#include <iostream>
#include <cmath> 
#include <iomanip>
#include <cstdlib>
#include <time.h>
#include <string> 
#include <cctype>    // 包含字符处理函数,大小写转换 , 大小写转换的方法 
using namespace std;


int main(int argc, char *argv[])
{
        cout << "Enter you password: ";
	string password;
	cin >> password;
	if(password.size()<8)
	{
		cout << "password " << password << " is not valid" << endl;
		cout << "length " << password.size() << endl;
	}
	   
    else   // 满足条件1 
    {
   	   int flag=0;
   	   int count_number = 0;
   	   for(int index=0; index<password.length(); index++)
   	   {
   	   	  if((tolower(password[index])>='0' && tolower(password[index])<='9') || (tolower(password[index])>='a' || tolower(password[index])<='z'))
   	   	  {
  	   	      if(password[index]>='0' && password[index]<='9')
				   count_number++;  // 统计数字的数量   	
   	      }
   	      else
		  {
  		      flag = 1;
			  break;	
  		  } 
   	   }
   	   
   	   // cout << "flag " << flag << "count_number " << count_number << endl; 
	   if(flag==0 && count_number>=2)
	   {
   		   cout << "password " << password << " is valid" <<endl;
   	   }  	
   	   else
   	   {
   	   	   cout << "password " << password << " is not valid" <<endl;
   	   }
 
    }
    return 0;
}


问题:

求解一元二次方程:

ax*x+bx+c=0

根据求根公式编写代码:

#include <iostream>
#include <cmath> 
#include <iomanip>
#include <cstdlib>
#include <time.h>
#include <string> 
#include <cctype>    // 包含字符处理函数,大小写转换 , 大小写转换的方法 
using namespace std;


int main(int argc, char *argv[])
{
        cout << "Solve the equation: ax*x+bx+c=0" << endl;
	cout << "Enter the coeffient of the equation(a!=0): ";
	int a, b, c;
	cin >> a >> b >> c;
	int delta = pow(b,2.0) - 4*a*c;
	if(delta>=0)  // 方程有实数根 
	{
	  if(delta>0)  // 两个不同的实根 
	  {
  		 float r1, r2;
  		 r1 = (-b+sqrt(delta))/2*a;
  		 r2 = (-b-sqrt(delta))/2*a;
	     cout << "r1=" << r1 << endl;
		 cout << "r2=" << r2 << endl; 
  	  }
	  else        // 两个相等的实数根 
	  {
  	     float r;
		 r = (-b)/(2*a);
		 cout << "The solution of the equation is: " << endl; 	
		 cout << "r1=" << r << endl;
		 cout << "r2=" << r << endl; 
  	  }  	
	}
	else         // 虚数根 
	{
	   delta = -1 * delta;
	   float real, imaginary;
       real = -1.0*b/(2*a);
	   imaginary = sqrt(delta) / (2.0*a);
	   cout << "The solution of the equation is: " << endl;	   
	   cout << "r1=" << real << "+" << imaginary << "i" << endl;
	   cout << "r2=" << real << "-" << imaginary << "i" << endl;
	} 
	return 0;
}


测试结果:

判断两个直线是否相交,如果相交,求解两个直线的交点

#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;

// 判断两条直线的交点
void cal_Intersection(double, double, double, double, double, double, double, double, double&, double&, bool&);
 
int main(int argc, char *argv[])
{
	double x, y;  // intersection point
	bool intersection;
	cout << "输入直线的端点坐标: " << endl;
	cout << "Line 1: ";
	double l1_x1, l1_y1, l1_x2, l1_y2;
	cin >> l1_x1 >> l1_y1 >> l1_x2 >> l1_y2;
	cout << "Line 2: ";
	double l2_x1, l2_y1, l2_x2, l2_y2;
	cin >> l2_x1 >> l2_y1 >> l2_x2 >> l2_y2;
	
	cal_Intersection(l1_x1, l1_y1, l1_x2, l1_y2, l2_x1, l2_y1, l2_x2, l2_y2, x, y, intersection);
	cout << intersection << endl;
	if(intersection)
	{
		cout << "The cross point is (" << x << "," << y << ")." << endl; 
		//cout << x << " " << y;
	}
	else
	{
		cout << "The two line has no cross point!" << endl;
		//cout << x << " " << y;
	}
	return 0;
}


void cal_Intersection(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, double& x, double& y, bool& isIntersection)
{
	// 根据直线的方程
	// ax+by=e
	// cx+dy=f
	double a = y2 - y1;
	double b = -1 * (x2 - x1);
	double e = x2*(y2 - y1) - y2*(x2 - x1);
	
	double c = y4 - y3;
	double d = -1 * (x4 - x3);
	double f = x4*(y4 - y3) - y4*(x4 - x3);
	
	if(abs(a*d - b*c)<0.0001) // 方程无解 
	{
		x = 0;
		y = 0;
		isIntersection = false;
	}
	else  // 方程有解 
	{
	        x = (e*d - b*f) / (a*d - b*c);
		y = (a*f - e*c) / (a*d - b*c);
		if(x1 < x2)  // 消除点的先后次序对结果的影响 
		{
	            if(x>x1 && x<x2)
		       isIntersection = true;
                    else
                       isIntersection = false;
		}
	        else
	        {
    		    if(x>x2 && x<x1)
		       isIntersection = true;
                    else
                       isIntersection  = false;
    	        }
	} 
}
   	
 

信用卡号码校验:
开头4: visa card

开头5: mastercard card

开头37: America express card

开头6: Discover card;

Luhn校验法:

判断信用卡号是否合法:

code:

#include <iostream>
#include <string>
#include <iomanip>
 
using namespace std;

int cardTypeCode(string);
void cardType(string, string&);
int sumOfEven(string);
int sumOfOdd(string);
bool isValid(string);

int main(int argc, char *argv[])
{
    // 信用卡号码校验
    string card_number;
    string card_type;
    
	cout << "Enter your card number: ";
	cin >> card_number;
    if(isValid(card_number))
    {
    	cardType(card_number, card_type);
    	cout << "The card is valid, the card type is " << card_type << endl;
    }
    else
    {
    	cout << "The card is invalid" << endl;
    }
	return 0;
}


int cardTypeCode(string card)
{
	// 根据信用卡的卡号返回卡的类型
    if(card[0]=='4')   // Visa card
       return 1;
    else if(card[0]=='5')   // Mastercard
       return 2;
    else if(card[0]=='3' && card[1]=='7') // America express card
       return 3;
    else if(card[0]=='6')     // Discovery card
       return 4;
    else  // other card
       return 0;
}

void cardType(string card, string& cardTypeString)
{
	switch (cardTypeCode(card))
	{
		case 0: cardTypeString = "Other card"; break;
		case 1: cardTypeString = "Visa card";  break;
		case 2: cardTypeString = "MasterCard card"; break;
		case 3: cardTypeString = "America express card"; break;
		case 4: cardTypeString = "Discover card"; break;
	}   	
}

int sumOfEven(string card)   
{
	// 从右向左偶位数*2
	int sum_even = 0;
	int counter = 0;  // 计数器 
	for(int i=card.length()-1; i>=0; i--)
	{ 
	   int current_number = 0 + card[i] - '0';
	   counter++;
	   if(counter%2==0) // 偶数位的数字
	   {
	   	   //cout << "current number: " << current_number << endl;
	       if(2*current_number>9)
		   {
		   	   current_number = current_number * 2;
		   	   int a = current_number % 10;  // 存储各位 
		   	   int b = current_number / 10;  // 存储十位数 
			   sum_even += (a+b); 
		   }
	       else
	       {
	   	      sum_even += current_number*2;
	       }
	  } 
	    
	}
	return sum_even;  
} 

int sumOfOdd(string card)
{
	int sum_odd = 0;
	int counter = 0;
	for(int i=card.length()-1; i>=0; i--)
	{
		int current_number = 0 + card[i] - '0';
	    counter++;
	    if(counter%2==1)
	    {
    		sum_odd += current_number;
    	}
	}
	return sum_odd;
}


bool isValid(string card)
{
   if((sumOfEven(card)+sumOfOdd(card))%10==0)
      return true;
   else
      return false;	
}

 

 

 

 

 

 

 

 

 

 

 

posted @ 2018-10-05 11:26  Alpha205  阅读(114)  评论(0编辑  收藏  举报