1. 程式人生 > >C++課後題(1)

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;	
}