5.1(統計正數和負數的數目,計算平均值)撰寫程式,讀入整數(數目未定),判定讀入的整數中有多少正數,多少負數,并計算這些整數的總和與平均值(0不計算在內),如果讀入0,程式即終止,平均值以浮點數顯示,
#include <iostream>
using namespace std;
int main()
{
int numberOfPositives = 0;//正數的數目
int numberOfNegatives = 0;//負數的數目
int total = 0;//所有整數的和
double average = 0;//所有整數的平均值
int digit;//用戶輸入的數字
//提示用戶輸入一行整數
cout << "Enter an integer ,the input ends if it is 0:";
do
{
cin >> digit;
if (digit > 0)//如果輸入大于0為正數
numberOfPositives++;//正數數目加一
else if (digit < 0)//如果輸入小于0為負數
numberOfNegatives++;//負數數目加一
total += digit;//把每次輸入的數都加到總和中
} while (digit);//如果輸入是0停止回圈
//如果正數負數的數目都為0,證明沒有輸入,輸出提示資訊
if (numberOfNegatives == 0 && numberOfPositives == 0)
{
cout << "No number are entered except 0" << endl;
return 0;//直接結束函式,不再進行運算
}
//計算平均值=總和/總數,總數=(正數個數+負數個數)
average = total / ((double)numberOfNegatives + numberOfPositives);
//輸出
cout << "The number of positives is " << numberOfPositives << endl;
cout << "The number of negatives is " << numberOfNegatives << endl;
cout << "The total is " << total << endl;
cout << "The average is " << average << endl;
return 0;
}
5.2(重復加法練習)程式清單5-4生成10個隨機的減法題,修改程式,使之能生成10個隨機的加法題,要求兩個運算元是1~15之間的整數,顯示回答正確的題數和測驗所用的時間,
#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
int correctCount = 0;//答對題目的數量
int count = 0;//答題的數目
long startTime = time(0);//答題開始時間
const int NUMBER_OF_QUESTIONS = 15;//系統默認的每次答題個數
srand(time(0));//設定隨機種子
while (count < NUMBER_OF_QUESTIONS)
{
//生成兩個亂數
int number1 = rand() % 15;
int number2 = rand() % 15;
//輸出兩個數相加的提示資訊
cout << "What is " << number1 << " + " << number2 << " ?";
int answer;
cin >> answer;//用戶輸入答案
//判斷輸入是否正確
if (answer == (number1 + number2))
{
cout << "You are correct!\n\n";
correctCount++;
}
else
{
cout << "Your answer is wrong.\n" << number1 << " + " << number2
<< " shoule be " << number1 + number2 << "\n" << endl;
}
//答題數目加一
count++;
}
long endTime = time(0);//答題結束時間
long testTime = endTime - startTime;//總答題時間=開始時間-結束時間
//輸出
cout << "\nCorrect count is " << correctCount << "\nTest time is " << testTime << " seconds\n" << endl;
return 0;
}
5.3(將千克數轉換為磅數)撰寫程式,輸出下表(注意1千克等于2.2磅)

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double KILOGRAMS_TO_POUNDS = 2.2;
cout << left;//設定輸出左對齊
cout << setw(10) << "Kilograms" << "\t" << "Pounds" << endl;
for (int i = 1; i < 200; i++)
{
cout << left;
cout << setw(10) << i << "\t" << i * KILOGRAMS_TO_POUNDS << endl;
}
return 0;
}
5.4(將英里數轉換為千米數)撰寫程式,輸出下表(注意1英里等于1.609千米)

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double MILES_TO_KILOMETERS = 1.609;
cout << left;//設定輸出左對齊
cout << setw(10) << "Miles" << "\t" << "Kilometers" << endl;
for (int i = 1; i < 11; i++)
{
cout << left;
cout << setw(10) << i << "\t" << fixed << setprecision(3) << i * MILES_TO_KILOMETERS << endl;
}
return 0;
}
5.5(將千克數轉換為磅數,將磅數轉換為千克數)撰寫程式,顯示下面兩個并排的表(注意1千克等于2.2磅),

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double KILOGRAMS_TO_POUNDS = 2.2;
cout << left;//設定輸出左對齊
cout << setw(10) << "Kilograms" << "\t" << "Pounds" << "\t|" << "\t" << "Pounds\t" << "Kilograms" << endl;
for (int i = 1; i < 200; i += 2)
{
cout << left;
cout << setw(10) << fixed << setprecision(2) << i << "\t" << i * KILOGRAMS_TO_POUNDS << "\t|"
<< "\t" << i * 2.5 + 17.5 << "\t" << (i * 2.5 + 17.5) / KILOGRAMS_TO_POUNDS << endl;
}
return 0;
}
5.6(將英里數轉換為千米數,將千米數轉換為英里數)撰寫程式,輸出下面兩個并排的表(注意1英里等于1.609千米),

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double MILES_TO_KILOMENTERS = 1.609;
cout << left;//設定輸出左對齊
cout << setw(10) << "Miles" << "\t" << "Kilomenters" << "\t|" << "\t" << "Kilomenters\t" << "Miles" << endl;
for (int i = 1; i < 11; i ++)
{
cout << left;
cout << setw(10) << fixed << setprecision(3) << i << "\t" << i * MILES_TO_KILOMENTERS << "\t\t|"
<< "\t" << i * 5 + 15 << "\t" << (i * 5 + 15) / MILES_TO_KILOMENTERS << endl;
}
return 0;
}
5.7(使用三角函式)輸出下串列格,顯示0~360度中以10度為單位增長的度數相應的sin值與cos值,精確到小數點后四位,

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
const double PI = 3.1416;
cout << setw(10) << left << "Degree" << "\t" << "Sin" << "\t" << "Cos" << endl;
for (int i = 0; i <= 360; i += 10)
{
cout << setw(10) << left << i << fixed << setprecision(4) << "\t" <<
sin(i / 360.0 * 2 * PI) << "\t" << cos(i / 360.0 * 2 * PI) << endl;
}
return 0;
}
5.8(使用sqrt函式)使用sqrt函式撰寫程式來輸出下串列格,

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
cout << setw(10) << left << "Number" << "\t" << "SquareRoot" << endl;
for (int i = 0; i <= 20; i += 2)
{
cout << setw(10) << left << i << "\t" << fixed << setprecision(4) << sqrt(i) << endl;
}
return 0;
}
5.9(金融應用:計算未來的學費)假定一所大學今年的學費為10000美元,且以每年5%的幅度增長,撰寫一個程式,使用回圈計算10年內的學費,撰寫另一個程式,計算10年內以每年為開始的四年大學的總學費,
//計算10年內的學費
#include <iostream>
using namespace std;
int main()
{
const double BASED_TUITION = 10000;//基礎學費
const double RATE_OF_YEAR = 0.05;//每年的增長幅度
double currentTuition = BASED_TUITION;
for (int i = 1; i < 10; i++)
{
currentTuition *= (1.0 + RATE_OF_YEAR);
cout << "從今年開始,往后第" << i << "年的學費為" << currentTuition << "美元" << endl;
}
return 0;
}
//計算往后10年,每四年的學費
#include <iostream>
using namespace std;
int main()
{
const double BASED_TUITION = 10000;//基礎學費
const double RATE_OF_YEAR = 0.05;//每年的增長幅度
double currentTuition = BASED_TUITION;//當前年份的學費(因為從第一年開始,所以初始值為基礎學費BASED_TUITION)
double totalTuition;//四年學費總額
//第一層回圈,現在是第幾年
for (int i = 1; i < 10; i++)
{
totalTuition = 0;//當前學費總額為清零
currentTuition *= (1.0 + RATE_OF_YEAR);//第i年的學費
double currentTuitionTemp = currentTuition;//將當前第i年的學費賦給臨時變數,以供下面的for回圈使用
//第二層回圈,在今年的基礎上,計算總共四年的總和
for (int j = 0; j < 4; j++)
{
totalTuition += currentTuitionTemp;
currentTuitionTemp *= (1.0 + RATE_OF_YEAR);
}
cout << "從第" << i << "年開始,四年的總的學費為" << totalTuition << "美元" << endl;
}
return 0;
}
5.10(求最高成績)撰寫一個程式,由用戶輸入學生數和每個學生的姓名及成績,最終輸出成績最高的學生的姓名和成績,
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numberOfStudent;//學生數目
string name;//考生姓名
double score;//考試分數
string maxName;//最高分的學生姓名
double maxScore = 0.0;//最高分的學生分數
cout << "請輸入學生數:";
cin >> numberOfStudent;
for (int i = 0; i < numberOfStudent; i++)
{
cout << "\n請輸入學生姓名:";
cin >> name;
cout << "\n請輸入學生分數:";
cin >> score;
if (score > maxScore)
{
maxScore = score;
maxName = name;
}
}
cout << "\n成績最高的學生姓名為:" << maxName << ",分數為:" << maxScore << endl;
return 0;
}
5.11(求最高的兩個成績)撰寫一個程式,提示用戶輸入學生數和每個學生的姓名及成績,程式輸出最高成績和成績排在第二位的學生的姓名和成績,
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numberOfStudent;//學生數目
string name;//考生姓名
double score;//考試分數
string firstName;//最高分的學生姓名
double firstScore = 0.0;//最高分的學生分數
string secondName;//成績排第二位的學生姓名
double secondScore = 0.0;//成績排第二位的學生分數
cout << "請輸入學生數:";
cin >> numberOfStudent;
for (int i = 0; i < numberOfStudent; i++)
{
cout << "\n請輸入學生姓名:";
cin >> name;
cout << "\n請輸入學生分數:";
cin >> score;
if (score > firstScore)//如果本次輸入大于當前最高分
{
secondName = firstName;//將當前的第一名變為第二名
secondScore = firstScore;//將當前的最高分變為第二名的分數
firstScore = score;//本次輸入的分數為現有最高分
firstName = name;//本次輸入的姓名為現有最高分的姓名
}
else if (score > secondScore)//本次輸入小于當前最高分,但大于第二名的分數
{
secondName = name;
secondScore = score;
}
}
cout << "\n成績最高的學生姓名為:" << firstName << ",分數為:" << firstScore << endl;
cout << "\n成績第二的學生姓名為:" << secondName << ",分數為:" << secondScore << endl;
return 0;
}
5.12(求同時能被5和6整除的數)撰寫程式,輸出100~1000之間所有能同時被5和6整除的整數,每行輸出10個,數字間由空格分開,
#include<iostream>
using namespace std;
int main()
{
const int BEGIN_NUMBER = 100;//開始遍歷的數字
const int END_NUMBER = 1000;//結束遍歷的數字
const int NUMBER_OF_PRIMES_PER_LINE = 10;//每行顯示多少個數字
int count = 0;//當前能同時整除5和6的整數的數量
for (int i = BEGIN_NUMBER; i <= END_NUMBER; i++)
{
if (i % 5 == 0 && i % 6 == 0)//判斷是否能同時被5和6整除
{
cout << i << " ";//該數字能被5和6同時整除,輸出此數字,用空格隔開
count++;//當前整除的數量加一
if (count % NUMBER_OF_PRIMES_PER_LINE == 0)//如果當前數量為10的整數,換行
cout << endl;
}
}
return 0;
}
5.13(求能被5/6之一整除的數)撰寫程式,輸出100~200之間所有能被5和6之一整除的,且只被兩者之一整除的整數,每行顯示10個,數字間由空格分開,
#include<iostream>
using namespace std;
int main()
{
const int BEGIN_NUMBER = 100;//開始遍歷的數字
const int END_NUMBER = 200;//結束遍歷的數字
const int NUMBER_OF_PRIMES_PER_LINE = 10;//每行顯示多少個數字
int count = 0;//當前能只整除5或6的整數的數量
for (int i = BEGIN_NUMBER; i <= END_NUMBER; i++)
{
if ((i % 5 == 0 && i % 6 != 0) || (i % 5 != 0 && i % 6 == 0))//判斷是否能被5和6之一且只被之一整除
{
cout << i << " ";//該數字能被5或6之一且只被之一整除,輸出此數字,用空格隔開
count++;//當前整除的數量加一
if (count % NUMBER_OF_PRIMES_PER_LINE == 0)//如果當前數量為10的整數,換行
cout << endl;
}
}
return 0;
}
5.14(求滿足>12000的最小的n)使用一個while回圈,求平方值大于12000的最小整數n,
#include <iostream>
using namespace std;
int main()
{
const int SQUARED_VALVE = 12000;//平方值
int n = 0;
while (n * n <= SQUARED_VALVE)
n++;
cout << "平方值大于" << SQUARED_VALVE << "的最小整數n為:" << n;
return 0;
}
5.15(求滿足<12000的最大的n)使用一個while回圈,求立方值小于12000的最大整數n,
#include <iostream>
using namespace std;
int main()
{
const int SQUARED_VALVE = 12000;//立方值
int n = 0;
while (n * n * n <= SQUARED_VALVE)//當前n的立方大于SQUARED_VALVE的時候跳出回圈
n++;
cout << "平方值大于" << SQUARED_VALVE << "的最小整數n為:" << n - 1;//則n-1即為最大值
return 0;
}
5.16(計算最大公約數)程式清單5-10之外的另一種求兩個整數n1和n2的最大公約數的方法如下:首先求n1和n2中較小的那個值d,然后按順序檢查d、d-1、d-2、……、2或1是否能同時整除n1和n2.第一個檢查到的公約數顯然就是n1和n2的最大公約數,撰寫程式,提示用戶輸入兩個正整數,輸出最大公約數,
#include <iostream>
using namespace std;
int main()
{
int firstInteger;//第一個整數
int secondInteger;//第二個整數
//提示用戶輸入第一個整數
cout << "Enter first integer:";
cin >> firstInteger;
//提示用戶輸入第二個整數
cout << "Enter second integer:";
cin >> secondInteger;
//回圈遍歷最大公約數,取兩個整數中較小的賦值給i
for (int i = firstInteger < secondInteger ? firstInteger : secondInteger; i > 0; i--)
{
//如果i能同時被兩個整數整除,則i就是最大公約數,輸出i,跳出回圈
if (secondInteger % i == 0 && firstInteger % i == 0)
{
cout << "The greaat common divisor for " << firstInteger << " and " << secondInteger << " is " << i << endl;
break;
}
}
return 0;
}
5.17(輸出ASCII字符表)撰寫一個程式,列印ASCII字符表中從!到~之間的字符,每行列印10個字符,ASCII表在附錄B中顯示,字符由空格分開,
#include <iostream>
using namespace std;
int main()
{
const int NUMBER_OF_PRIMES_PER_LINE = 10;//每行顯示多少個數字
for (char i = '!'; i <= '~'; i++)
{
if ((i - '!') % NUMBER_OF_PRIMES_PER_LINE == 0)
cout << endl;
cout << i << " ";
}
return 0;
}
5.18(求一個整數的因子)撰寫一個程式,讀入一個整數,由小至大顯示其所有因子,例如,如果輸入整數為120,輸出應該是:2、2、2、3、5,
#include <iostream>
using namespace std;
int main()
{
int number;//用戶輸入的整數
cout << "請輸入一個整數:";
cin >> number;
//從2開始回圈到小于number
for (int i = 2; i <= number; i++)
{
//如果i能被number整除
if (number % i == 0)
{
cout << i << " ";//i就是number的因子
number /= i;//number此時已提取出一個因子,將number的值除以該因子,得到新的number值
i = 1;//將i的值置為1(因為for中有i++,置為1,i++以后就變為了2,還是從2開始回圈的),繼續新number的回圈,提取因子
}
}
return 0;
}
5.19(輸出金字塔)撰寫程式,提示用戶輸入1~15中的某個數字,輸出金字塔圖案,

#include <iostream>
using namespace std;
int main()
{
int numberOfLine;
cout << "Enter the number of lines:";
cin >> numberOfLine;
for (int i = 1; i <= numberOfLine; i++)
{
for (int j = numberOfLine; j >= i; j--)
cout << "\t";
for (int k = i; k >= 1; k--)
cout << k << "\t";
for (int k = 2; k <= i; k++)
cout << k << "\t";
cout << endl;
}
return 0;
}
5.20(用回圈列印4個圖案)使用嵌套回圈撰寫4個程式,分別輸出下面四個圖形,

#include <iostream>
using namespace std;
int main()
{
//Pattern A
cout << "Pattern A" << endl;
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= i; j++)
cout << j << "\t";
cout << endl;
}
cout << "Pattern B" << endl;
//Pattern B
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 6 - i + 1; j++)
cout << j << "\t";
cout << endl;
}
cout << "Pattern C" << endl;
//Pattern C
for (int i = 1; i <= 6; i++)
{
for (int j = i; j >= 1; j--)
cout << j << "\t";
cout << endl;
}
cout << "Pattern D" << endl;
//Pattern D
for (int i = 1; i <= 6; i++)
{
for (int j = 1; j <= 6 - i + 1; j++)
cout << j << "\t";
cout << endl;
}
return 0;
}
5.21(輸出一個數字金字塔圖案)撰寫一個嵌入的for回圈,輸出下面的圖案:

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
for (int i = 1; i <= 8; i++)
{
for (int j = 7 - i + 1; j >= 0; j--)
cout << "\t";
for (int k = 1; k <= i; k++)
cout << pow(2, k - 1) << "\t";
for (int z = i - 1; z >= 1; z--)
cout << pow(2, z - 1) << "\t";
cout << endl;
}
return 0;
}
5.22(輸出2~1000之間的素數)修改程式清單5-17,輸出2~1000(包含2和1000)之間的所有素數,每行顯示8個,數字由空格分開,
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int BEGIN_NUMBER = 2;//開始遍歷的數字
const int END_NUMBER = 1000;//結束遍歷的數字
const int NUMBER_OF_PRIMES_PER_LINE = 8;//每行輸出幾個素數
bool isPrimesFlag = true;//該數是否是素數的標記字符
int countOfPrimes = 0;//當前素數個數
//第一層回圈,從BEGIN_NUMBER到END_NUMBER對每個數進行遍歷
for (int i = BEGIN_NUMBER; i <= END_NUMBER; i++)
{
//對第i個數判斷是否為素數,只需在它的1/2大小的數中找約數
for (int j = 2; j <= i/2; j++)
{
if (i % j == 0)//如果存在除了1和本身的其他約數
{
isPrimesFlag = false;//素數標記符設為false
break;//跳出回圈
}
}
//如果是素數,列印該數,素數的個數加一
if (isPrimesFlag)
{
cout << setw(5) << left << i << " ";
countOfPrimes++;
}
//如果素數的個數等于每行輸出素數個數的要求
if (countOfPrimes == NUMBER_OF_PRIMES_PER_LINE)
{
cout << endl;//換行
countOfPrimes = 0;//素數計數置零
}
isPrimesFlag = true;//將標記位設定為ture
}
return 0;
}
5.23(金融應用:比較不同利率下的還款金額)撰寫一個程式,由用戶輸入貸款額和貸款年限,輸出不同利率下的月還款額和總還款額,利率從5%~8%,增長間隔為1/8.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
const double INTERST_RATE = 0.05;//最初的利率
const double FINAL_RATE = 0.08;//最終的利率
const double INYERVAL_BETWEEN_INTERESTT_RATE_INCREASES = 1 / 800.0;//利率增長間隔
double loanAmount;//貸款額
int numberOfYears;//貸款年限
double currentYearRate = INTERST_RATE;//當前回圈中的年利率
double currentMonthRate;//當前年利率下的月利率
double currentMonthlyPayment;//當前利率下的月還款額
double currentTotalPayment;//當前利率下的總還款額
//提示用戶輸入貸款額
cout << "Loan Amount:";
cin >> loanAmount;
//提示用戶輸入貸款年限
cout << "Number of Years:";
cin >> numberOfYears;
//輸出表頭
cout << "\nInterest Rate" << "\t" << "Monthly Payment" << "\t" << "Total Payment" << endl;
//回圈進行每年的計算
for (int i = 0; i <= (FINAL_RATE - INTERST_RATE) / INYERVAL_BETWEEN_INTERESTT_RATE_INCREASES; i++)
{
currentMonthRate = currentYearRate / 12.0;//當次回圈中的月利率=當次回圈的年利率/12.0
//月還款額
currentMonthlyPayment = loanAmount * currentMonthRate / (1.0 - 1.0 / pow((1.0 + currentMonthRate), numberOfYears * 12));
//總還款額
currentTotalPayment = currentMonthlyPayment * numberOfYears * 12;
cout << fixed << setprecision(3) << currentYearRate * 100.0 << "%\t\t"
<< setprecision(2) << currentMonthlyPayment << "\t\t"
<< setprecision(2) << currentTotalPayment << endl;
currentYearRate += INYERVAL_BETWEEN_INTERESTT_RATE_INCREASES;
}
return 0;
}
5.24(金融應用:貸款分期償還計劃)一筆貸款的月還款包括償還本金和償還利息,月利息可以通過月利率乘以余額(剩余本金)來計算,于是月償還本金就等于月還款減去月償還利息,撰寫一個程式,由用戶輸入貸款額、貸款年限和利率,輸出分期還款的計劃,
提示:最后一次還款后的余額可能不是0.如果是這種情況,那么應在最后一次還款額應該是正常的月還款額加上最終的余額,
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
double loanAmount;//貸款總額
double numberOfYear;//貸款年限
double annualInterestRate;//年利率
cout << "Loan Amount:";
cin >> loanAmount;
cout << "Number of Years:";
cin >> numberOfYear;
cout << "Annual Interest Rate:";
cin >> annualInterestRate;
double interest;//利息
double principal;//本金
double balance = loanAmount;//余額
//月還款額
double monthlyPayment = (loanAmount * annualInterestRate / 1200.0) / (1 - 1 / pow(1 + annualInterestRate / 1200.0, numberOfYear * 12));
//還款總額
double totalPayment = monthlyPayment * numberOfYear * 12;
cout << "\nMonthly Payment:" << fixed << setprecision(2) << monthlyPayment;
cout << "\nTotal Payment:" << fixed << setprecision(2) << totalPayment << endl;
//輸出表頭
cout << "Payment#" << "\t" << "Interest" << "\t" << "Principal" << "\t" << "Balance" << endl;
for (int i = 1; i <= numberOfYear * 12; i++)
{
//利息=月利率*余額
interest = annualInterestRate / 1200.0 * balance;
//還款本金=月還款-利息
principal = monthlyPayment - interest;
//余額=當前余額-還款本金
balance = balance - principal;
cout << i << "\t\t" << fixed << setprecision(2) << interest << "\t\t" << principal << "\t\t" << balance << endl;
}
return 0;
}
5.25(演示消去誤差)當一個很大的數與一個很小的數進行運算時,可能會發生消去誤差,大數可能抵消掉小數,例如,1000000000.0+0.000000001的結果是100000000.0.為了避免消去誤差,獲得更精確的結果,應小心選擇計算對的階,例如,當計算如下級數時,由右至左計算就會比由左至右計算獲得更精確的結果:
撰寫一個程式,計算上面級數的和,由左至右計算一次,再由右至左計算一次,n=50000.
#include <iostream>
using namespace std;
int main()
{
const int N = 50000;//級數層數
double sumOfLeftToRight = 0.0;//從左向右求和
double sumOfRightToLeft = 0.0;//從右向左求和
for (int i = 1; i <= N; i++)
sumOfLeftToRight += 1.0 / (double)i;
cout << "從左向右求和為:" << sumOfLeftToRight << endl;
for (int i = N; i > 0; i--)
sumOfRightToLeft += 1.0 / (double)i;
cout << "從右向左求和為:" << sumOfRightToLeft << endl;
return 0;
}
5.26(計算一個級數的和)撰寫程式,計算下面級數的和:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double sum = 0.0;
for (int i = 1; i < 99; i += 2)
sum = (double)i / (double)(i + 2);
cout << "級數為:" << sum << endl;
return 0;
}
5.27(計算π)可以使用下面的級數來逼近π:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int N = 500000;//設定級數層數
double pi = 0.0;//π初始值
//回圈計算級數
for (int i = 1; i < N; i++)
pi += pow(-1, i + 1) / ((2 * (double)i) - 1.0);
pi *= 4;
cout << "級數為" << N << "時,逼近的π值為:" << pi << endl;
return 0;
}
5.28(計算e)可以使用下面的級數來逼近e:
#include <iostream>
using namespace std;
int main()
{
const int N = 20;//級數層數
double e = 0.0;//e
int factorial = 1;//階乘
for (int i = 0; i < N; i++)
{
//計算階乘
for (int j = 1; j <= i; j++)
factorial *= j;
//用級數計算e
e += 1 / (double)factorial;
factorial = 1;//將階乘重新置為1
}
cout << N << "層級數逼近e為:" << e << endl;
return 0;
}
5.29(顯示閏年)撰寫一個程式,輸出21世界(2001-2100年)中所有的閏年,每行輸出10項,閏年之間間隔為一個空格,
#include <iostream>
using namespace std;
int main()
{
const int NUMBER_PER_LINE = 10;//每行顯示個數
const int BEGIN_YEAR = 2001;//開始年份
const int END_YEAR = 2100;//結束年份
int numberOfLeapYear = 0;//計數閏年
for (int i = BEGIN_YEAR; i <= END_YEAR; i++)
{
//判斷是否為閏年
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
{
cout << i << " ";
numberOfLeapYear++;
//判斷是否換行
if (numberOfLeapYear % 10 == 0)
cout << endl;
}
}
return 0;
}
5.30(顯示每個月的第一天)撰寫程式,提示用戶輸入一個年份及這年的第一天是星期幾,輸出每個月的第一天是星期幾,例如,如果用戶輸入2013和2,表示2013年1月1日是星期二,程式應輸出如下內容:
January 1,2013 is Tuesday
……
December 1,2013 is Sunday
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int NUMBER_OF_DAYS_A_WEEK = 7;//一星期中有幾天
int year;//年份,用戶輸入
int weekday;//當前年份的一月一日是星期幾,用戶輸入
cout << "請輸入年份和當年的一月一日是星期幾:";
cin >> year >> weekday;
cout << endl;
int month_num;//月份數字表示
//月份,字串表示
string month_str[12] = { "January","February","March","April",
"May","June","July","August","September",
"October","November","December" };
//星期,字串表示
string week_str[7] = { "Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday" };
int dayNumber = 0;//從year的第一天到當前月份第一天的總天數
//回圈遍歷每個月
for (month_num = 0; month_num < 12; month_num++)
{
dayNumber = 0;
switch (month_num)
{
case 12:
dayNumber += 31;
case 11:
dayNumber += 30;
case 10:
dayNumber += 31;
case 9:
dayNumber += 30;
case 8:
dayNumber += 31;
case 7:
dayNumber += 31;
case 6:
dayNumber += 30;
case 5:
dayNumber += 31;
case 4:
dayNumber += 30;
case 3:
dayNumber += 31;
case 2:
//判斷是否為閏年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
dayNumber += 29;
else
dayNumber += 28;
case 1:
dayNumber += 31; break;
defaule:break;
}
cout << month_str[month_num] << " 1," << year << " is " << week_str[(dayNumber + weekday) % 7] << endl;
}
return 0;
}
5.31(輸出日歷)撰寫程式,提示用戶輸入年份和這一年的第一天是星期幾,輸出這一年的日歷,例如,如果用戶輸入2013和2,表示2013年1月1日是星期二,則程式應輸出此年中每個月的日歷,

#include <iostream>
#include <string>
using namespace std;
int main()
{
const int NUMBER_OF_DAYS_A_WEEK = 7;//一星期中有幾天
int year;//年份,用戶輸入
int weekday;//當前年份的一月一日是星期幾,用戶輸入
cout << "請輸入年份和當年的一月一日是星期幾:";
cin >> year >> weekday;
cout << endl;
int fristDayOfMonth;//每個月的第一天是星期幾
int month_num;//月份數字表示
//月份,字串表示
string month_str[12] = { "January","February","March","April",
"May","June","July","August","September",
"October","November","December" };
//每個月有多少天
int DayNumberOfMonth[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
//判斷是否為閏年,閏年的時,二月份為29天
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
DayNumberOfMonth[1] = 29;
else
DayNumberOfMonth[1] = 28;
int dayNumber = 0;//從year的第一天到當前月份第一天的總天數
//回圈遍歷每個月,得出當前月份的第一天到當年1月1號的總天數
for (month_num = 0; month_num < 12; month_num++)
{
dayNumber = 0;
switch (month_num)
{
case 12:
dayNumber += 31;
case 11:
dayNumber += 30;
case 10:
dayNumber += 31;
case 9:
dayNumber += 30;
case 8:
dayNumber += 31;
case 7:
dayNumber += 31;
case 6:
dayNumber += 30;
case 5:
dayNumber += 31;
case 4:
dayNumber += 30;
case 3:
dayNumber += 31;
case 2:
//判斷是否為閏年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
dayNumber += 29;
else
dayNumber += 28;
case 1:
dayNumber += 31; break;
defaule:break;
}
cout << "\t\t" << month_str[month_num] << " " << year << endl;//輸出表頭
cout << "----------------------------------------------------------" << endl;//輸出表頭
cout << "Sun" << "\t" << "Mon" << "\t" << "Tue" << "\t" << "Wed" << "\t" << "Thu" << "\t" << "Fri" << "\t" << "Sat" << endl;//輸出表頭
int i;//回圈變數
int flagOfLine = 0;//換行標志位
fristDayOfMonth = (dayNumber + weekday) % 7;//計算當前月份的第一天是星期幾
//第一列是星期日,根據當前的星期幾,計算第一行需要輸出幾次空格
for (i = 0; i < fristDayOfMonth % NUMBER_OF_DAYS_A_WEEK; i++)
{
cout << " " << "\t";
flagOfLine++;//換行符加1
}
//列印輸出表的主要內容
for (int j = 1; j <= DayNumberOfMonth[month_num]; j++)
{
cout << j << "\t";
flagOfLine++;
//判斷是否需要換行
if (flagOfLine == NUMBER_OF_DAYS_A_WEEK)
{
cout << "\n" << endl;
flagOfLine = 0;//清零,重新計數
}
}
cout << "\n\n";
}
return 0;
}
5.32(金融應用:計算零取整存)假定你每月向一個儲蓄賬戶存入100美元,利率是5%,那么,月利率是0.05/12=0.00417.第一個月后,賬面金額變為:100*(1+0.00417)=100.417
第二個月后,賬面金額變為:(100+100.417)*(1+0.00417)=201.252
第三個月后,賬面金額變為:(100+201.252)*(1+0.00417)=302.507
以此類推,撰寫一個程式,提示用戶輸入每月存入金額(如100)、年利率(如5)、月數(如6),輸出指定月數后賬面金額,
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double monthlyDepositAmount = 0.0;//月存入金額
double annualInterestRate = 0.0;//年利率
double monthlyInterestRate = 0.0;//月利率
int numberOfMonth = 0;//月數
double totalSum = 0.0;//總額
cout << "輸入月存入金額:" << endl;
cin >> monthlyDepositAmount;
cout << "輸入年利率:" << endl;
cin >> annualInterestRate;
cout << "輸入月數:" << endl;
cin >> numberOfMonth;
monthlyInterestRate = annualInterestRate / 1200.0;
for (int i = 0; i < numberOfMonth; i++)
{
totalSum = (monthlyDepositAmount + totalSum) * (1.0 + monthlyInterestRate);
}
cout << numberOfMonth << "月后,賬面金額為:" << totalSum << endl;
return 0;
}
5.33(金融應用:計算CD價值)假定你向CD投入10 000美元,年度百分比收益率為5.75%,一個月后,CD價值為
10 000+10 000*5.75/1200=10047.91
第二個月后,CD價值為:10047.91+10047.91*5.75/1200=10096.06
第三個月后,CD價值為:10096.06+10096.06*5.75/1200=10144.43
以此類推,撰寫程式,提示用戶輸入金額(如10000)、年度百分比收益率(如5.75)和月數(如18),輸出表格,

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double initialAmount = 0.0;//初始存入金額
double annualRate = 0.0;//年利率
unsigned int numberOfMonth = 0;//月數
double totalSum = 0.0;//CD價值,總金額
cout << "Enter the initial deposit amount:";
cin >> initialAmount;
cout << "Enter annual percentage yield:";
cin >> annualRate;
cout << "Enter maturity period (number of months):";
cin >> numberOfMonth;
cout << "Month" << "\t" << "CD Value" << endl;
totalSum = initialAmount;
for (int i = 1; i <= numberOfMonth; i++)
{
totalSum = totalSum + totalSum * annualRate / 1200.0;
cout << i << "\t" << fixed << setprecision(2) << totalSum << endl;
}
return 0;
}
5.34(游戲:彩票)重寫程式清單3-7,Lottery.cpp,生成一個兩位數的彩票,一個數中的兩個數字不同,(提示:生成第一個數字,使用回圈重復生成第二個數字,直到它同第一個數字不同)
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
//生成兩個不相同的亂數
srand(time(0));
int lotteryDigit1 = rand() % 10;//亂數1
int lotteryDigit2 = rand() % 10;//亂數2
//如果兩個亂數相同,進入回圈
while (lotteryDigit1 == lotteryDigit2)
lotteryDigit2 = rand() % 10;//重新生成亂數2
cout << "Enter your lottery pick (two digits):";
int guess;
cin >> guess;
int guessDigit1 = guess / 10;
int guessDigit2 = guess % 10;
cout << "The lottery number is " << lotteryDigit1 << lotteryDigit2 << endl;
if (guessDigit1 == lotteryDigit1 && guessDigit2 == lotteryDigit2)
cout << "Exact match: you win $10,000" << endl;
else if (guessDigit2 == lotteryDigit1 && guessDigit1 == lotteryDigit2)
cout << "Macth all digits: you win $3,000" << endl;
else if (guessDigit1 == lotteryDigit1 || guessDigit1 == lotteryDigit2 || guessDigit2 == lotteryDigit1 || guessDigit2 == lotteryDigit2)
cout << "Match one digit:you win $1,000" << endl;
else
cout << "Sorry,no match" << endl;
return 0;
}
5.35(完全數)如果一個正整數等于它的所有正因子(不包括它本身)之和,則這個正整數稱為完全數,例如,6為第一個完全數,因為6=3+2+1.下一個為28=14+7+4+2+1.小于10 000的完全數有四個,撰寫程式找出這4個數字,
#include <iostream>
using namespace std;
int main()
{
const int BEGIN_NUMBER = 1;//開始遍歷數字
const int END_NUMBER = 10000;//結束遍歷數字
int sum = 0;//正因子之和
for (int i = BEGIN_NUMBER; i < END_NUMBER; i++)
{
for (int j = 1; j <= i / 2; j++)
{
if (i % j == 0)//如果是因子
sum += j;//
}
if (sum == i)//判斷因子總和和該數是否相等
cout << i << endl;
sum = 0;
}
return 0;
}
5.36(游戲:剪刀,石頭,布)程式設計練習3.15給出了玩剪刀石頭布游戲的程式,重寫程式,使其一直進行直到用戶或計算機贏兩次以上,
#include<iostream>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
int numberOfUserWin = 0;//用戶贏的次數
int numberOfComputerWin = 0;//電腦贏的次數
srand(time(0));
while (numberOfComputerWin < 2 && numberOfUserWin < 2)
{
int computerInput = rand() % 3;//電腦隨機得到一個0,1,2的數
//提示用戶輸入
cout << "scissor(0),rock(1),paper(2):";
int userInput;
cin >> userInput;
//輸出電腦是剪刀石頭還是布
cout << "The computer is ";
switch (computerInput)
{
case 0:cout << "scissor"; break;
case 1:cout << "rock"; break;
case 2:cout << "paper"; break;
};
//輸出用戶的剪刀石頭還是布
cout << ". You are ";
switch (userInput)
{
case 0:cout << "scissor"; break;
case 1:cout << "rock"; break;
case 2:cout << "paper"; break;
default:cout << "inputting is error"; return 0;
};
if (computerInput == userInput)//相等則平局
cout << " too. It is a draw" << endl;
else if (userInput == 0 && computerInput == 2 || userInput == 1 && computerInput == 0
|| userInput == 2 && computerInput == 1)
{
cout << ". You won" << endl;
numberOfUserWin++;
}
else
{
cout << ". You loss" << endl;
numberOfComputerWin++;
}
}
return 0;
}
5.37(求和)撰寫程式計算下列數的總和,
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int BEGIN_NUMBER = 1;
const int END_NUMBER = 625;
double total = 0.0;
for (int i = BEGIN_NUMBER; i < END_NUMBER - 1; i++)
total += 1.0 / (sqrt(i) + sqrt(i + 1));
cout << "數列的總和為:" << total << endl;
return 0;
}
5.38(商業應用:檢測ISBN)使用回圈來簡化程式設計練習3.35.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << "Enter the first 9 digits of an ISBN as integer:";
int isbn_10;//用戶輸入ISBN的前九位數字
cin >> isbn_10;
int digit;//中間變數,用來臨時存放第n位ISBN值
int sum = 0;//九個數字計算出來的總和
cout << "The ISBN-10 number is ";
//輸出前九位數字
for (int i = 9; i > 0; i--)
{
digit = (isbn_10 % (int)pow(10, i)) / ((int)pow(10, i - 1));
cout << digit;//輸出該位數字
sum += digit * (10 - i);//累加和
}
if (sum % 11 == 10)//如果校驗和為10,輸出為X
cout << "X" << endl;
else
cout << sum % 11 << endl;
return 0;
}
5.39(金融應用:計算出銷售額)你剛剛在百貨公司開始做銷售作業,你的工資包括基礎工資與提成,基礎工資為$5000.下面的計劃表來決定提成率,注意,這是一個累進稅率,第一個$5000為8%,第二個$5000為10%,剩下的為12%,如果你銷售額為25 000,則提成為5000*8%+5000*10%+15 000*12%=2700,你的目標是每年賺$30 000.撰寫程式,使用do-while回圈,計算出賺取$30 000需要最少的銷售額,
#include <iostream>
using namespace std;
const float BASIC_WAGE = 5000.0;//基礎工資
const float TARGET_WAGE = 30000.0;//目標工資
const float FIRST_STAGE = 0.0; //第一階段
const float FIRST_STAGE_RATE = 8.0; //第一階段稅率
const float SECOND_STAGE = 5000.0; //第二階段
const float SECOND_STAGE_RATE = 10.0; //第二階段稅率
const float THIRD_STAGE = 10000.0; //第三階段
const float THIRD_STAGE_RATE = 12.0; //第三階段稅率
int main()
{
float sale = 0.0;//銷售額
float wage = BASIC_WAGE;//總工資
do
{
wage = BASIC_WAGE;//總工資
if (sale > FIRST_STAGE && sale <= SECOND_STAGE)
wage += sale * FIRST_STAGE_RATE / 100.0;//第一階段
else if (sale > SECOND_STAGE && sale <= THIRD_STAGE)
wage += SECOND_STAGE * FIRST_STAGE_RATE / 100.0 +//第一階段
(sale - SECOND_STAGE) * SECOND_STAGE_RATE / 100.0;//第二階段
else if (sale > THIRD_STAGE)
wage += SECOND_STAGE * FIRST_STAGE_RATE / 100.0 +//第一階段
(THIRD_STAGE - SECOND_STAGE) * SECOND_STAGE_RATE / 100.0 +//第二階段
(sale - THIRD_STAGE) * THIRD_STAGE_RATE / 100.0;//第三階段
sale += 0.01;//每次增加一分錢
} while (wage <= TARGET_WAGE);//當總工資大于每年工資目標結束回圈
cout << "賺取$" << TARGET_WAGE << "需要最少$" << sale << "銷售額" << endl;
return 0;
}
5.40(模擬實驗:正面或背面)撰寫程式,模擬拋硬幣1百萬次,輸出正面與背面出現的次數,
#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
const int NUMBER = 1000000;//設定次數為一百萬次
srand(time(0));
int front = 0;//正面出現次數
int reverse = 0;//反面出現次數
int i = NUMBER;//回圈次數
while (i--)
if (rand() % 2)//奇數即對2取余為1的數為正面
front++;
else//偶數為反面
reverse++;
cout << "正面出現次數:" << front << ",反面出現次數:" << reverse << endl;
return 0;
}
5.41(最大數出現的次數)撰寫程式,讀取整數,找出其中的最大值,并計算它出現的次數,規定輸入以數字0為結尾,假定你輸入3 5 2 5 5 5 0;那么程式找出最大值為5,它出現的次數為4.(提示:創建兩個變數max和count,max存盤當前最大的數字,count存盤它出現的次數,初始化時,將第一個數字賦給max,1賦給count,與max比較子序列中的每個數字,如果數字大于max,將他賦給max,將count重置為1.如果數字等于max,則將count加1)
#include <iostream>
using namespace std;
int main()
{
int max, count = 0;
cout << "Enter number:";
cin >> max;
//如果只輸入一個0,結束程式
if (max == 0)
return 0;
else//輸入第一個數不為0,count加1
++count;
while (1)
{
int number;
cin >> number;
if (number == 0)//0為結尾數字,遇到0結束回圈
break;
else if (number < max)//小于最大值,跳出本次回圈
continue;
else if (number == max)//等于最大值,最大值出現次數加一
++count;
else//大于最大值,最大值重新賦值,最大值數量變為1
max = number, count = 1;
}
cout << "The largest number is " << max << endl
<< "The occurrence count of the largest number is " << count << endl;
return 0;
}
5.42(金融應用:計算銷售額)重新撰寫程式設計練習5.39,要去如下:
使用for回圈代替do-while回圈,
讓用戶輸入COMMISSON_SOUGHT,而不是將它設定為常量,
#include <iostream>
using namespace std;
const float BASIC_WAGE = 5000.0;//基礎工資
//const float TARGET_WAGE = 30000.0;//目標工資
const float FIRST_STAGE = 0.0; //第一階段
const float FIRST_STAGE_RATE = 8.0; //第一階段稅率
const float SECOND_STAGE = 5000.0; //第二階段
const float SECOND_STAGE_RATE = 10.0; //第二階段稅率
const float THIRD_STAGE = 10000.0; //第三階段
const float THIRD_STAGE_RATE = 12.0; //第三階段稅率
int main()
{
float COMMISSION_SOUGHT;//期待工資
cout << "請輸入COMMISSION_SOUGHT期待總工資:";
cin >> COMMISSION_SOUGHT;
float sale = 0.0;//銷售額
//當總工資大于每年工資目標結束回圈
for (float wage = BASIC_WAGE; wage <= COMMISSION_SOUGHT; sale += 0.01)//每次增加一分錢
{
wage = BASIC_WAGE;//總工資
if (sale > FIRST_STAGE && sale <= SECOND_STAGE)
wage += sale * FIRST_STAGE_RATE / 100.0;//第一階段
else if (sale > SECOND_STAGE && sale <= THIRD_STAGE)
wage += SECOND_STAGE * FIRST_STAGE_RATE / 100.0 +//第一階段
(sale - SECOND_STAGE) * SECOND_STAGE_RATE / 100.0;//第二階段
else if (sale > THIRD_STAGE)
wage += SECOND_STAGE * FIRST_STAGE_RATE / 100.0 +//第一階段
(THIRD_STAGE - SECOND_STAGE) * SECOND_STAGE_RATE / 100.0 +//第二階段
(sale - THIRD_STAGE) * THIRD_STAGE_RATE / 100.0;//第三階段
}
cout << "賺取$" << COMMISSION_SOUGHT << "需要最少$" << sale << "銷售額" << endl;
return 0;
}
5.43(模擬實驗:倒計時)撰寫程式,提示用戶輸入秒數,每一秒均顯示資訊,當時間用完時程式結束,
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
//獲取用戶輸入秒數
cout << "Enter the number of seconds:";
int seconds;
cin >> seconds;
//獲取當前總秒數
int totalTime = time(0);
while (seconds > 0)
{
while ((time(0) - totalTime) == 0);//回圈等待,經過一秒后跳出回圈
totalTime = time(0);//將totalTIme付志偉·重新賦值為當前總秒數
cout << seconds;
//判斷second單詞的單復數形式
if (seconds == 1)
cout << " second";
else
cout << " seconds";
cout << " remaining" << endl;
seconds--;
}
cout << "Stopped";
return 0;
}
5.44(蒙特卡洛模擬實驗)一個正方形分為4個小的區域,如果向正方形投擲飛鏢1 000 000次,那么飛鏢進入奇數區域的可能性是多少?撰寫程式模擬程序并輸出結果,

#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
int area1 = 0, area2 = 0, area3 = 0, area4 = 0;
int times = 1000000;//投擲飛鏢的次數
srand(time(0));
float den = RAND_MAX / 2.0;//將分母設定為亂數最大值的一半
while (times--)
{
int number = rand();//產生x坐標的亂數
float point_X = float(number - den) / den;
number = rand();//產生y坐標的亂數
float point_Y = float(number - den) / den;
//如果x的坐標值小于0,則該點在區域1
if (point_X < 0)
area1++;
//x坐標不小于0,y坐標小于0,則點在區域4
else if (point_Y < 0)
area4++;
//橫縱坐標之和小于1,該點在區域3
else if (point_X + point_Y < 1)
area3++;
//橫縱坐標大于0,且之和大于1,該點在區域2
else
area4++;
}
cout << "飛鏢飛入奇數區域的可能性為:" << float(area1+area3)/float(area1+area2+area3+area4) << endl;
return 0;
}
5.45(數學:組合)撰寫程式,輸出整數1~7內兩個數字的所有可能的組合,同時,輸出所有組合的總的個數,
#include <iostream>
using namespace std;
int main()
{
const int BEGIN_DIGIT = 1;//開頭的數字
const int END_DIGIT = 7;//結尾的數字
unsigned int number = 0;//數字組合的計數變數
for (int i = BEGIN_DIGIT; i <= END_DIGIT; i++)
{
for (int j = i + 1; j <= END_DIGIT; j++)
{
cout << i << "\t" << j << "" << endl;
number++;
}
}
cout << "The total number of all combinations is " << number;
return 0;
}
5.46(計算機系統結構:位操作)一個short值占16位,撰寫程式,提示用戶輸入一個short型別的整數,輸出這個整數的16位表示,
#include <iostream>
using namespace std;
int main()
{
//獲取用戶輸入的short型整數
cout << "Enter an integer:";
short integer;
cin >> integer;
for (int bits = 0; bits < sizeof(short) * 8; bits++)
{
//獲取每一位元位
short bit;
bit = integer << bits;
bit = bit >> (sizeof(short) * 8 - 1);
cout <<"The bits are "<<abs(bit);
}
return 0;
}
5.47(統計學:計算均值和標準差)在商業應用中,經常會需要計算資料的均值與標準差,均值為數字的平均值,標準差為一個統計數值,告訴你一組資料中所有資料是多緊密地聚集在均值周圍,例如,一個班中學生的平均年齡為多少?年齡有多相近?如果所有同學都為相同的年齡,則標準差為0.撰寫程式,提示用戶輸入10個數字,使用下列公式輸出這些數字的均值和標準差:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//獲取用戶輸入的十個整數
cout << "Enter ten numbers:";
float n = 10.0;//整數個數
float number[10] = { 0.0 };
for (int i = 0; i < 10; i++)
cin >> number[i];
//總數
float total = 0;
//計算平均值
float mean = 0.0;
for (int i = 0; i < 10; i++)
total += number[i];
mean = total / n;
//計算標準差
float deviation = 0.0;
total = 0.0;
for (int i = 0; i < 10; i++)
total += (number[i] - mean) * (number[i] - mean);
deviation = sqrt(total / (n-1));
cout << "The mean is " << mean << endl;
cout << "The standard deviation is " << deviation << endl;
return 0;
}
5.48(計算大寫字母)撰寫一個程式,提示用戶輸入一個字串,輸出字串中大寫字母的個數,
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter a string : ";
string str;
getline(cin, str);//讀取一行
int count = 0;//大寫字母數量
for (int i = 0; i < str.length(); i++)
if (str[i] >= 'A' && str[i] <= 'Z')
count++;
cout << "The number of uppercase letter is " << count;
return 0;
}
5.49(最長公共前綴)撰寫程式,提示用戶輸入兩個字串,輸出字串的最長公共前綴,
#include <iostream>
#include <string>
using namespace std;
int main()
{
//獲取用戶輸入的s1字串
cout << "Enter s1:";
string s1;
getline(cin, s1);
//獲取用戶輸入的s2字串
cout << "Enter s2:";
string s2;
getline(cin, s2);
//定義共同前綴變數
string commonPrefix;
//遍歷尋找共同前綴
for (int i = 0; i < min(s1.length(), s2.length()); i++)
{
if (s1[i] == s2[i])
commonPrefix.push_back(s1[i]);//如果相同,將該字符壓入變數末尾
else
break;
}
if (commonPrefix.length() == 0)
cout << s1 << " and " << s2 << " have no common prefix";
else
cout << "The common prefix is " << commonPrefix;
return 0;
}
5.50(倒置字串)撰寫程式,提示用戶輸入字串,以相反順序輸出字串,
#include <iostream>
#include <string>
using namespace std;
int main()
{
//獲取用戶輸入的字串
cout << "Enter a string:";
string str;
getline(cin, str);
//反順序輸出
cout << "The reversed string is ";
for (int i = str.length(); i > 0; i--)
cout << str[i - 1];
return 0;
}
5.51(商業:檢測ISBN-13)ISBN-13為識別圖書的新的標準,它使用13個數字d1d2d3d4d5d6d7d8d9d10d11d12d13,最后一個數字d13為校驗和,使用下列公式由其他數字得出:
10-(d1=3d2+d3+3d4+d5+3d6+d7+3d8+d9+3d10+d11+3d12)%10
如果校驗和為10,則用0來代替,程式應該將輸入讀取為字串,
#include <iostream>
#include <string>
using namespace std;
int main()
{
//獲取用戶輸入的前12個數字
cout << "Enter the first 12 digits of an ISBN-13 as a string:";
string ISBN_13;
cin >> ISBN_13;
//如果不足12個,列印提示資訊,結束程式
if (ISBN_13.length() < 12)
{
cout << ISBN_13 << " is an invalid input";
return 0;
}
//將string型別轉換為整數int
int isbn[12] = { 0 };
for (int i = 0; i < ISBN_13.length(); i++)
isbn[i] = ISBN_13[i] - '0';
//計算d13
int d13 = 0;
for (int i = 0; i < ISBN_13.length(); i++)
if (i % 2 == 0)
d13 += isbn[i];
else
d13 += 3 * isbn[i];
d13 = 10 - (d13 % 10);
//判斷d13是否為10
cout << ISBN_13;
if (d13 == 10)
cout << 0;
else
cout << d13;
return 0;
}
5.52(處理字串)撰寫程式,提示用戶輸入字串,輸出奇數下標位置的字符,
#include <iostream>
#include <string>
using namespace std;
int main()
{
//獲取用戶輸入的字串
cout << "Enter a string:";
string str;
getline(cin,str);
//輸出奇數下標位置字符
for (int i = 0; i < str.length(); i++)
if (i % 2 == 1)
cout << str[i];
return 0;
}
5.53(計算元音和輔音)將字母A、E、I、O、U定為元音,撰寫程式,提示用戶輸入字串,輸出字串中元音和輔音的個數,
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
//獲取用戶輸入的字串
cout << "Enter a string:";
string str;
getline(cin, str);
int numberOfVowels = 0;//元音字母個數
int numberOfConsonants = 0;//輔音字母個數
//遍歷判斷每一個字符屬于元音還是輔音
for (int i = 0; i < str.length(); i++)
{
//元音
if (str[i] == 'A' || str[i] == 'a'
|| str[i] == 'E' || str[i] == 'e'
|| str[i] == 'I' || str[i] == 'i'
|| str[i] == 'O' || str[i] == 'o'
|| str[i] == 'U' || str[i] == 'u')
numberOfVowels++;
//輔音,判斷是否為字母,否則可能把空格、數字等算作字母
else if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
numberOfConsonants++;
}
cout << "The number of vowels is " << numberOfVowels << endl;
cout << "The number of consonants is " << numberOfConsonants << endl;
return 0;
}
5.54(計算檔案中字母的個數)撰寫程式,計算名為countletter.txt檔案中字母的個數,在本題中我隨機生成了一個countletter.txt檔案,詳情見代碼,
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
//隨機生成一個字串
srand(time(0));
string str;
for (int i = 0; i < 100; i++)
str.push_back(char(rand() % 128));//ASCII碼值
//將這個字串存盤到檔案中并保存
ofstream makeFile;
makeFile.open("countletter.txt");
makeFile << str << endl;
makeFile.close();
//打開檔案,讀取字串
ifstream readFile;
readFile.open("countletter.txt");
string data;
readFile >> data;
readFile.close();
//遍歷查看字串中有多少個字母
int numberOfLetter = 0;
for (int i = 0; i < str.length(); i++)
if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z')
numberOfLetter++;
cout << "countletter.txt檔案中字母的個數為:" << numberOfLetter << endl;
return 0;
}
5.55(數學輔導)撰寫程式,輸出運行樣例中所示的選單,輸入1/2/3/4選擇加法、減法、乘法、或者除法測驗,在測驗結束后,選單會重新顯示,你可以選擇另一個測驗或者輸入5退出系統,每個測驗隨機生成兩個僅有一個數字的數,對于減法來說,number1-number2,number1大于或等于number2.對于除法來說,number1/number2,number2不為0.
#include <iostream>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
srand(time(0));
int number1, number2;
while (1)
{
//生成選單欄
cout << "Main menu\n"
<< "1: Addition\n"
<< "2: Subtraction\n"
<< "3: Multiplication\n"
<< "4: Division\n"
<< "5: Exit\n"
<< "Enter a choice: ";
int choice;//用戶選擇的序號
cin >> choice;//用戶輸入序號
int answer;//用戶輸入的答案
number1 = rand() % 10;//生成一個亂數
number2 = rand() % 10;
switch (choice)
{
case 1://加法
cout << "What is " << number1 << " + " << number2 << "? ";
cin >> answer;
if (answer == number1 + number2)
cout << "Correct\n\n";
else
cout << "Your answer is wrong, The correct answer is " << number1 + number2 << "\n\n";
break;
case 2://減法,減法中第一個數字要大于第二個數字,所以取兩個亂數中的較大值作為第一個數,較小值作為第二個數
cout << "What is " << max(number1, number2) << " - " << min(number1, number2) << "? ";
cin >> answer;
if (answer == abs(number1 - number2))
cout << "Correct\n\n";
else
cout << "Your answer is wrong, The correct answer is " << abs(number1 - number2) << "\n\n";
break;
case 3://乘法
cout << "What is " << number1 << " × " << number2 << "? ";
cin >> answer;
if (answer == number1 * number2)
cout << "Correct\n\n";
else
cout << "Your answer is wrong, The correct answer is " << number1 * number2 << "\n\n";
break;
case 4://除法
//判斷number2是否為0
if (number2 == 0)//如果number2為0,則進去while回圈
while ((number2 = rand() % 10) == 0);//直到number2得到一個不為0的亂數,跳出回圈
cout << "What is " << number1 << " / " << number2 << "? ";
cin >> answer;
if (answer == number1 / number2)
cout << "Correct\n\n";
else
cout << "Your answer is wrong, The correct answer is " << number1 + number2 << "\n\n";
break;
case 5://退出程式
cout << "exit" << endl;
return 0;
default:
break;
}
}
return 0;
}
5.56(拐點坐標)假定一個有n條邊的正多邊形中心為(0,0),一個點在3點鐘方向,撰寫程式,提示用戶輸入邊的個數和正多邊形外接圓的半徑,輸出正多邊形拐點的坐標,
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//定義常量PI
const float PI = 3.14159;
//獲取用戶輸入的多邊形的邊數
cout << "Enter the number of the sides: ";
int numbersOfSides;
cin >> numbersOfSides;
//獲取圓的半徑
cout << "Enter the radius of the bounding circle: ";
float radius;
cin >> radius;
//輸出多邊形各個頂點的坐標
cout << "The coordinates of the points on the polygon are" << endl;
for (int i = 0; i < numbersOfSides; i++)
{
float x = radius * cos(2 * PI / numbersOfSides * i);
float y = radius * sin(2 * PI / numbersOfSides * i);
cout << "(" << x << ", " << y << ")" << endl;
}
return 0;
}
5.57(檢測密碼)有些網站施加一些對密碼的規定,假定密碼規則如下:
- 密碼必須有至少8位字符
- 密碼必須僅包含字母和數字
- 密碼必須包含至少兩個數字
撰寫程式,提示用戶輸入密碼,如果遵循了密碼規則,則顯示vaild password,否則顯示invalid password,
#include <iostream>
#include <string>
using namespace std;
int main()
{
string password;//密碼字串,用戶輸入
cout << "Please put in a password: ";
cin >> password;
int numberOfDigit = 0;//密碼中包含數字的數量
int numberOfLetter = 0;//密碼中包含字母的數量
int numberOfOthers = 0;//密碼中包含的其他符號
//判斷規則一:密碼必須有至少8位字符
if (password.length() >= 8)
{
for (int i = 0; i < password.length(); i++)
{
//判斷是否為數字
if (password[i] >= '0' && password[i] <= '9')
numberOfDigit++;
//判斷是否為字母
else if (password[i] >= 'a' && password[i] <= 'z' || password[i] >= 'A' && password[i] <= 'Z')
numberOfLetter++;
//其他字符
else
{
numberOfOthers++;
break;//跳出回圈,因為違反規則2僅包含字母和數字
}
}
//判斷是否符合規則2和規則3
if (numberOfOthers == 0 && numberOfDigit >= 2 && numberOfLetter > 0)
{
cout << "valid password";
return 0;
}
else
{
cout << "invalid password";
return 0;
}
}
else
cout << "invalid password";
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/253984.html
標籤:其他
上一篇:pgzero/pygame zero新手教程,pgzero/pygame zero教程,如何使用pgzero/pygame zero
