《C++程序设计》 Y.Daniel Liang 著 第七章习题答案

例7.1

·(设计等级)编写程序,读入学生分数,得到最好的分数并根据下面的计划设计分数等级:
G r a d e Grade Grade A A A,如果 s c o r e > = b e s t − 10 score>=best-10 score>=best10
G r a d e Grade Grade B B B,如果 s c o r e > = b e s t − 20 score>=best-20 score>=best20
G r a d e Grade Grade C C C,如果 s c o r e > = b e s t − 30 score>=best-30 score>=best30
G r a d e Grade Grade D D D,如果 s c o r e > = b e s t − 40 score>=best-40 score>=best40
G r a d e Grade Grade F F F,其他。
程序先提示用户输入学生总数,然后提示用户输入所有成绩,最后显示分数等级。

#include<iostream>
using namespace std;

int max(int list[], int listSize){
    int max = list[0];
    for (int i = 1; i < listSize; i++){
        if (list[i] > max)
            max = list[i];
    }

    return max;
}

void scoreGrade(int list[], int listSize, int best){
    for (int i = 0; i < listSize; i++){
        if (list[i] >= best - 10)
            cout << "Student " << i << " score is " << list[i] << " and grade is A" << endl;
        else if (list[i] >= best - 20)
            cout << "Student " << i << " score is " << list[i] << " and grade is B" << endl;
        else if (list[i] >= best - 30)
            cout << "Student " << i << " score is " << list[i] << " and grade is C" << endl;
        else if (list[i] >= best - 40)
            cout << "Student " << i << " score is " << list[i] << " and grade is D" << endl;
        else
            cout << "Student " << i << " score is " << list[i] << " and grade is F" << endl;
    }
}

int main(){
    cout << "Enter the number of students: ";
    int n;
    cin >> n;

    cout << "Enter " << n << " scores: ";
    const int N = n;
    int score[N];
    for (int i = 0; i < n; i++)
        cin >> score[i];

    scoreGrade(score, n, max(score, n));

    return 0;
}

例7.2

·(将输入整数的顺序反转)编写一个程序,读入10个整数,以输入的逆序输出它们。

#include<iostream>
using namespace std;

void reverse(int list[], int listSize){
    for (int i = listSize - 1; i >= 0; i--)
        cout << list[i] << " ";
}

int main(){
    cout << "输入10个整数: ";
    int list[10];
    for (int i = 0; i < 10; i++)
        cin >> list[i];

    reverse(list, 10);

    return 0;
}

例7.3

·(统计数字数目)编写一个程序,读入至多100个1 ~ 100之间的整数,数出每个数出现的次数。假定输入以0结束。

#include<iostream>
using namespace std;

int main(){
    int count[100] = {0};
    
    cout << "Enter the integers between 1 and 100: ";
    int number;
    cin >> number;
    while(number != 0){
        count[number - 1]++;
        cin >> number;
    }

    for (int i = 0; i < 100; i++){
        if (count[i] != 0)
            cout << i + 1 << " occurs " << count[i] << ((count[i] == 1) ? " time" : " times") << endl;
    }

    return 0;
}

例7.4

·(分析成绩)编写一个程序,读入若干成绩,数目未定,分析有多少成绩在平均成绩之上、之下及恰好相等。用户输入负数表示输入结束。假定成绩最高为100分。

#include<iostream>
using namespace std;

int main(){
    double counts[10000] = {0};
    double score;
    double total = 0;
    int count = 0;
    int i = 0;

    cout << "Enter the scores between 0 and 100: ";
    cin >> score;
    while (score > 0){
        total = total + score;
        count++;
        counts[i] = score;
        i++;
        cin >> score;
    }

    int max = 0;
    int min = 0;
    int mid = 0;
    for (int i = 0; i < count; i++){
        if (counts[i] > total / count)
            max++;
        else if (counts[i] < total / count)
            min++;
        else
            mid++;
    }

    cout << "平均成绩为:" << total / count << endl;
    cout << "平均成绩之上有:" << max << " 个" << endl;
    cout << "平均成绩之下有:" << min << " 个" << endl;
    cout << "平均成绩相等有:" << mid << " 个" << endl;

    return 0;
}

例7.5

·(打印不同的数)编写一个程序,读入10个数,输出其中不同的数(即如果一个数出现多次,只打印一次)。

#include<iostream>
using namespace std;

int main(){
    int number[10];
    int size = 0;

    cout << "Enter ten numbers: ";
    for (int i = 0; i < 10; i++){
        int value;
        cin >> value;

        bool isInArray = false;
        for (int j = 0; j < i && !isInArray; j++)
            if (number[j] == value)
                isInArray = true;

        if (!isInArray){
            number[size] = value;
            size++;
        }
    }

    cout << "The distinct numbers are: ";
    for (int i = 0; i < size; i++)
        cout << number[i] << " ";

    return 0;
}

例7.6

·(修改程序清单5-17)程序清单5-17通过检查一个数 n n n 是否能被 2 、 3 、 4 、 5 、 6 、 . . . 、 n / 2 2、3、4、5、6、...、n/2 23456...n/2 整除来判定 n n n 是否为素数。如果找到一个因子,则 n n n 不是素数。一个更有效的方法是,检查所有小于等于 n \sqrt{n} n 的素数是否能整除 n n n。如果均不能整除,则 n n n 是素数。用此方法重写程序清单5-17,输出前50个素数。你需要使用一个数组保存找到的素数,随后检查它们是否能整除 n n n

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

int main(){
    const int NUM_OF_PRIMES = 50;
    int primeNumbers[NUM_OF_PRIMES];
    int count = 0; // 记录素数的个数
    int number = 2; // 参与素数测试的数字
    bool isPrime = true; // 当前测试的数字是否是素数

    cout << "The first 50 prime numbers are: " << endl;

    while (count < NUM_OF_PRIMES){
        // 假定number是素数
        isPrime = true;

        // 测试number是否是素数
        for (int i = 0; i < count && primeNumbers[i] <= sqrt(1.0 * number); i++){
            // 如果能整除,则不是素数
            if (number % primeNumbers[i] == 0){
                // 将判断素数的标志设为false,跳出循环
                isPrime = false;
                break;
            }
        }

        // 如果number是素数,则加入素数数组
        if (isPrime){
            primeNumbers[count] = number;
            count++;

            // 每输出十个素数换行
            if (count % 10 == 0)
                cout << number << endl;
            else
                cout << number << "\t";
        }

        // 检查下一个number是否是素数
        number++;
    }

    return 0;
}

例7.7

·(统计数字数目)编写一个程序,随机生成100个0 ~ 9之间的随机整数,输出每个数出现的次数。(提示:使用 rand() % 10生成一个0 ~ 9之间的随机整数。使用一个包含10个整数的数组,比如说counts,保存0、1、…、9的出现次数。)

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

int main(){
    srand(time(0));

    int counts[10] = {0};

    for (int i = 0; i < 100; i++){
        int num = rand() % 10;
        counts[num]++;
    }

    for (int i = 0; i < 10; i++)
        cout << i << " 出现的次数为:" << counts[i] << endl;

    return 0;
}

例7.8

·(求数组均值)编写两个重载函数,返回一个数组中值的平均值,函数头如下:
int average ( const int array[ ], int size )
double average ( const double array[ ], int size )
编写测试程序,提示用户输入10个双精度数,调用这个函数并显示平均值。

#include<iostream>
using namespace std;

int average(const int array[], int size){
    int total = 0;
    for (int i = 0; i < size; i++)
        total = total + array[i];

    return total / size;
}

double average(const double array[], int size){
    double total = 0;
    for (int i = 0; i < size; i++)
        total = total + array[i];

    return total / size;
}

int main(){
    cout << "输入10个双精度数:";
    double list[10];
    for (int i = 0; i < 10; i++)
        cin >> list[i];

    cout << "平均值为:" << average(list, 10) << endl;

    return 0;
}

例7.9

·(求最小元素)使用如下函数头编写一个函数,求双精度数组中的最小元素。
double min ( double array[ ], int size )
编写测试程序,提示用户输入10个数字,调用这个函数并显示最小的值。

#include<iostream>
using namespace std;

double min(double array[], int size){
    double min = array[0];
    for (int i = 1; i < size; i++)
        if (min > array[i])
            min = array[i];

    return min;
}

int main(){
    cout << "Enter ten numbers: ";
    double list[10];
    for (int i = 0; i < 10; i++)
        cin >> list[i];

    cout << "The minimum number is " << min(list, 10) << endl;

    return 0;
}

例7.10

·(求最小元素的下标)编写一个函数,返回一个整型数组中最小元素的下标。如果有多个最小元素,返回最小的下标。请使用下面的函数头:
int indexOfSmallestElement ( double array[ ], int size )
编写测试程序,提示用户输入10个数字,调用这个函数返回最小元素的下标并显示出来。

#include<iostream>
using namespace std;

int indexOfSmallestElement(double array[], int size){
    double min = array[0];
    int index = 0;
    for (int i = 1; i < size; i++)
        if (min > array[i]){
            min = array[i];
            index = i;
        }

    return index;
}

int main(){
    cout << "Enter ten numbers: ";
    double list[10];
    for (int i = 0; i < 10; i++)
        cin >> list[i];

    cout << "The minimum number's index is " << indexOfSmallestElement(list, 10) << endl;

    return 0;
}

例7.11

·(统计:计算标准差)程序设计练习5.47计算一组数的标准差。本练习使用一个不同但等价的公式计算n个数的标准差:
   m e a n = ∑ i = 1 n x i n = x 1 + x 2 + . . . + x n n mean= \frac{\sum_{i=1}^n x_i}{n}=\frac{x_1 + x_2 + ... + x_n}{n} mean=ni=1nxi=nx1+x2+...+xn    d e v i a t i o n = ∑ i = 1 n ( x i − m e a n ) 2 n − 1 deviation=\sqrt{\frac{\sum_{i=1}^n (x_i - mean)^2}{n-1}} deviation=n1i=1n(ximean)2
为了用此公式计算标准差,你需要用一个数组保存每个数,在计算出均值后用这些数计算标准差。
程序应包含如下函数:
double mean ( const double x[ ], int size )
double deviation ( const double x[ ], int size )
编写测试程序,提示用户输入10个数字,并显示平均值和标准差。

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

double mean(const double x[], int size){
    double total = 0;
    for (int i = 0; i < size; i++)
        total += x[i];

    double mean = total / size;
    return mean;
}

double deviation(const double x[], int size){
    double temp = 0;
    double mean1 = mean(x, size);
    for (int i = 0; i < size; i++)
        temp += pow(x[i] - mean1, 2);
    double deviation = sqrt(temp / (size - 1));

    return deviation;
}

int main(){
    cout << "Enter ten numbers: ";
    double x[10];
    for (int i = 0; i < 10; i++)
        cin >> x[i];

    cout << "The mean is " << mean(x, 10) << endl;
    cout << "The standard deviation is " << deviation(x, 10) << endl;

    return 0;
}

例7.12

·(运行时间)编写一个程序,随机生成一个包含100000个整数的数组和一个关键字。计算调用程序清单7-9中 l i n e a r S e a r c h linearSearch linearSearch 函数所花费的时间。排序数组,然后计算调用程序清单7-10中 b i n a r y S e a r c h binarySearch binarySearch 函数所花费的时间。可用如下代码模板获取程序的运行时间:
long startTime = time(0);
perform the task;
long endTime = time(0);
long executionTime = endTime - startTime;

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

long linearSearch(const int list[], int key, int arraySize){
    long startTime = time(0);
    for (int i = 0; i < arraySize; i++){
        if (list[i] == key)
            break;
    }
    long endTime = time(0);
    long executionTime = endTime - startTime;
    return executionTime;
}

void selectionSort(int list[], int listSize){
    for (int i = 0; i < listSize - 1; i++){
        int currentMin = list[i];
        int currentMinIndex = i;

        for (int j = i + 1; j < listSize; j++){
            if (currentMin > list[j]){
                currentMin = list[j];         // 目前的最小值
                currentMinIndex = j;          // 目前最小值的索引
            }
        }

        if (currentMinIndex != i){
            list[currentMinIndex] = list[i];  // 把大值往后放
            list[i] = currentMin;             // 把小值往前放
        }
    }
}

int binarySearch(const int list[], int key, int listSize){
    long startTime = time(0);
    int low = 0;
    int high = listSize - 1;

    while (high >= low){
        int mid = (high + low) / 2;
        if (key < list[mid])
            high = mid - 1;
        else if (key == list[mid])
            return mid;
        else
            low = mid + 1;
    }

    long endTime = time(0);
    long executionTime = endTime - startTime;
    return executionTime;
}

int main(){
    srand(time(0));

    int key = rand() % 100;
    int list[100000];
    for (int i = 0; i < 100000; i++)
        list[i] = rand() % 100;

    long time1 = linearSearch(list, key, 100000);

    selectionSort(list, 100000);

    long time2 = binarySearch(list, key, 100000);

    cout << "顺序搜索时间:" << time1 << endl;
    cout << "二分搜索时间:" << time2 << endl;

    return 0;
}

例7.13

·(金融应用:求销售额)用二分搜索方法重写程序设计练习5.39。由于销售额在1 ~ COMMISSION_SOUGHT / 0.08 之间,因此可用二分搜索方法改进程序。

#include<iostream>
using namespace std;

int main(){
    const double COMMISSION_SOUGHT = 25000;

    double commission = 0;
    int low = 0;
    int high = (int)(COMMISSION_SOUGHT / 0.08);

    while (low < high - 1){
        int mid = (low + high) / 2;

        if (mid >= 10001)
            commission = 5000 * 0.08 + 5000 * 0.1 + (mid - 10000) * 0.12;
        else if (mid >= 5001)
            commission = 5000 * 0.08 + (mid - 5000) * 0.10;
        else
            commission = mid * 0.08;

        if (commission == COMMISSION_SOUGHT)
            break;
        else if (commission < COMMISSION_SOUGHT)
            low = mid;
        else
            high = mid;
    }

    cout << "The sales amount " << high << " is needed to make a commission of $" << COMMISSION_SOUGHT << endl;

    return 0;
}

例7.14

·(起泡排序)利用起泡排序算法编写一个排序函数。起泡排序算法分若干趟对数组进行处理。每趟处理中,对相邻元素进行比较。若为降序,则交换;否则,保持原排序。此技术被称为起泡排序( b u b b l e bubble bubble s o r t sort sort )或下沉排序( s i n k i n g sinking sinking s o r t sort sort ),因为较小的值逐渐地 “冒泡” 到上部,而较大值逐渐下沉到底部。
算法可描述如下:
bool changed = true;
do
{
  changed = false;
  for ( int j = 0; j < listSize - 1; j++ )
    if ( list[ j ] > list[ j + 1 ] )
    {
      swap list[ j ] with list[ j + 1 ];
      changed = true;
    }
} while ( changed );
很明显,循环结束后,列表变为升序。容易证明 do 循环最多执行 listSize - 1 次。
编写测试程序,读入一个含有10个双精度数字的数组,调用函数并显示排列后的数字。

#include<iostream>
using namespace std;

void bubbleSort(double list[], int listSize){
    bool changed = true;
    do {
        changed = false;
        for (int j = 0; j < listSize - 1; j++)
            if (list[j] > list[j + 1]){
                double temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
                changed = true;
            }
    } while (changed);
}

int main(){
    double list[10];
    for (int i = 0; i < 10; i++)
        cin >> list[i];

    bubbleSort(list, 10);

    for (int i = 0; i < 10; i++)
        cout << list[i] << " ";

    return 0;
}

例7.15

·(游戏:存物柜问题)一个学校有100个存物柜,100个学生。开学第一天所有存物柜都是关闭的。第一个学生(记为S1)来到学校后,打开所有存物柜。第二个学生S2,从第二个存物柜(记为L2)开始,每隔两个存物柜,将它们关闭。第三个学生S3从第三个存物柜L3开始,每隔三个,将它们的状态改变(开着的关上,关着的打开)。学生S4从L4开始,每隔四个改变它们的状态。学生S5从L5开始,每隔五个改变状态。依此类推,直至学生S100改变L100的状态。
当所有学生完成这个过程,哪些存物柜是开着的?编写一个程序求解此问题,显示所有开着的柜子的号码,号码之间用一个空格隔开。

#include<iostream>
using namespace std;

bool reverse(bool n){
    if (n)
        return false;
    else
        return true;
}

int main(){
    bool store[100];
    for (int i = 0; i < 100; i++)
        store[i] = false;

    int n = 1;
    while (n <= 100){
        for (int i = 0; i < 100; i++){
            if ((i + 1) % n == 0)
                store[i] = reverse(store[i]);
        }
        n++;
    }

    for (int i = 0; i < 100; i++){
        if (store[i])
            cout << "L" << i + 1 << " ";
    }

    return 0;
}

例7.16

·(修改选择排序)7.10节介绍了选择排序。方法是反复求当前(未排序)数组中最小元素,与数组首元素交换。重写程序,每个步骤找出最大最大元素,与数组尾元素交换。编写测试程序,读入一个由10个双精度数组成的数组,调用函数并显示排序后的数字。

#include<iostream>
using namespace std;

void selectionSort(double list[], int listSize){
    for (int i = listSize - 1; i >= 0 ; i--){
        double currentMax = list[i];
        int currentMaxIndex = i;

        for (int j = i - 1; j >= 0; j--){
            if (currentMax < list[j]){
                currentMax = list[j];
                currentMaxIndex = j;
            }
        }

        if (currentMaxIndex != i){
            list[currentMaxIndex] = list[i];
            list[i] = currentMax;
        }
    }
}

int main(){
    double list[10];
    cout << "输入10个双精度数: ";
    for (int i = 0; i < 10; i++)
        cin >> list[i];
    selectionSort(list, 10);

    cout << "排序后的: ";
    for (int i = 0; i < 10; i++){
        cout << list[i] << " ";
    }

    return 0;
}

例7.17

·(游戏:豆子机)豆子机也称梅花形或高尔顿盒子。它是用于统计实验的设备,以英国科学家弗朗西斯·高尔顿的名字命名。它由一个均匀钉上钉子的三角形竖直面板组成。
球从面板的开口处落下。每一次小球撞击钉子,它各有50%的概率落向左边和右边。这些球会累积在面板底部的狭缝里。
编写程序模拟豆子机。程序应该提示用户输入小球的数量和机器中狭缝的数量(最多50)。通过打印球的路径,模拟每一个球的下落状态。用柱状图显示最后小球的堆积方式。

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

/** 打印路径并返回落入的槽的位置,从0开始 */
int onePath(int numberOfSlots){
    int position = 0;
    for (int i = 0; i < numberOfSlots - 1; i++)
        if (rand() % 2 == 0)
            cout << "L";
        else{
            cout << "R";
            position++;
        }

    cout << endl;

    return position;
}

/** 返回slots[]最大值 */
int max(int slots[], int numberOfSlots){
    int max = slots[0];

    for (int i = 1; i < numberOfSlots; i++)
        if (max < slots[i])
            max = slots[i];

    return max;
}

/** 打印slot的直方图 */
void printHistogram(int slots[], int numberOfSlots){
    int maxSlotHeight = max(slots, numberOfSlots);

    for (int h = maxSlotHeight; h > 0; h--){
        for (int i = 0; i < numberOfSlots; i++)
            if (slots[i] < h)
                cout << " ";
            else
                cout << "O";

        cout << endl;
    }
}

int main(){
    srand(time(0));

    cout << "Enter the number of balls to drop: ";
    int numberOfBalls;
    cin >> numberOfBalls;

    cout << "Enter the number of slots in the bean machine: ";
    int numberOfSlots;
    cin >> numberOfSlots;

    int slots[50];

    for (int i = 0; i < numberOfSlots; i++)
        slots[i] = 0;

    for (int i = 0; i < numberOfBalls; i++)
        slots[onePath(numberOfSlots)]++;

    printHistogram(slots, numberOfSlots);

    return 0;
}

例7.18

·(游戏:八皇后)经典的八皇后问题就是把八个皇后放在棋盘上,使得没有两个皇后能攻击到对方(即没有两个皇后在同一行、同一列和同一对角线上)。这个问题有很多解。编写程序显示其中的一个解。下面是一个运行样例的输出结果:
| Q |  |  |  |  |  |  |  |
|  |  |  |  | Q |  |  |  |
|  |  |  |  |  |  |  | Q |
|  |  |  |  |  | Q |  |  |
|  |  | Q |  |  |  |  |  |
|  |  |  |  |  |  | Q |  |
|  | Q |  |  |  |  |  |  |
|  |  |  | Q |  |  |  |  |

/** 寻找八皇后问题的一个解 */
#include<iostream>
using namespace std;

int findPosition(int k, int queens[]);
bool isValid(int k, int j, int queens[]);
void printResult(int queens[]);
const int N = 8;

int main(){
    // 皇后位置
    int queens[N]; // 皇后的位置表示为:(i, queens[i])

    for (int i = 0; i < N; i++)
        queens[i] = -1; // -1表示目前没有皇后在第i行
    queens[0] = 0; // 先在第0行(0,0)处放置一个皇后

    // k-1表示到目前为止放置的皇后数量
    // 我们在第k行找一个位置放皇后
    int k = 1;
    while (k >= 0 && k <= N - 1){
        // 在第k行找到一个位置放置皇后
        int j = findPosition(k, queens);
        if (j < 0){
            queens[k] = -1;
            k--; // 返回到前一行
        }
        else{
            queens[k] = j;
            k++;
        }
    }

    printResult(queens);

    return 0;
}

int findPosition(int k, int queens[]){
    int start = queens[k] == -1 ? 0 : queens[k] + 1;

    for (int j = start; j < N; j++){
        if (isValid(k, j, queens))
            return j; // (k, j)是当前放置皇后的位置
    }

    return -1;
}

bool isValid(int k, int j, int queens[]){
    // 看看(k, j)是不是一个可能的位置
    // 检查第j列
    for (int i = 0; i < k; i++)
        if (queens[i] == j)
            return false;

    // 检查主对角
    for (int row = k - 1, column = j - 1; row >= 0 && column >= 0; row--, column--)
        if (queens[row] == column) return false;

    // 检查副对角
    for (int row = k - 1, column = j + 1; row >= 0 && column <= 7; row--, column++)
        if (queens[row] == column) return false;

    return true; // 有效
}

/** 打印一个二维表来显示皇后 */
void printResult(int queens[]){
    for (int i = 0; i < N; i++)
        cout << i << ", " << queens[i] << endl;
    cout << endl;

    // 显示输出
    for (int i = 0; i < N; i++){
        for (int j = 0; j < queens[i]; j++)
            cout << "| ";
        cout << "|Q|";
        for (int j = queens[i] + 1; j < N; j++)
            cout << " |";
        cout << endl;
    }
}

例7.19

·(游戏:多个八皇后问题的解)程序设计练习7.18找出了八皇后问题的一个解。编写程序计算所有可能的解并显示它们。

/** 找出八皇后问题的所有可能解 */
#include<iostream>
using namespace std;

int findPosition(int k, int queens[]);
bool isValid(int k, int j, int queens[]);
void printResult(int queens[]);

int numberOfSolutions = 0; // 找到了多少解?
const int N = 8;

int main(){
    // 皇后的位置
    int queens[N]; // 皇后的位置是(i, Queens [i])

    for (int i = 0; i < N; i++)
        queens[i] = -1; // -1表示目前没有皇后在第i行
    queens[0] = 0; // 先在第0行(0,0)处放置一个皇后

    // k-1表示到目前为止放置的皇后数量
    // 我们在第k行找一个位置放皇后
    int k = 1;
    while (k >= 0 && k <= N - 1){
        // 找到一个位置,把皇后放在第k行
        int j = findPosition(k, queens);
        if (j < 0){
            queens[k] = -1;
            k--; // 返回到前一行
        }
        else{
            queens[k] = j;

            if (k == N - 1) {
                numberOfSolutions++; // 找到一个解决方案
                cout << "Solution " << numberOfSolutions << ":" << endl;
                printResult(queens);
            }
            else
                k++;
        }
    }

    cout << "有多少个解? " << numberOfSolutions << endl;

    return 0;
}

int findPosition(int k, int queens[]){
    int start = queens[k] == -1 ? 0 : queens[k] + 1;

    for (int j = start; j < N; j++){
        if (isValid(k, j, queens))
            return j; // (k, j)是现在放皇后的地方
    }

    return -1;
}

bool isValid(int k, int j, int queens[]){
    // 看看(k, j)是不是一个可能的位置
    // 检查第j列
    for (int i = 0; i < k; i++)
        if (queens[i] == j)
            return false;

    // 检查主对角
    for (int row = k - 1, column = j - 1; row >= 0 && column >= 0; row--, column--)
        if (queens[row] == column) return false;

    // 检查副对角
    for (int row = k - 1, column = j + 1; row >= 0 && column <= N - 1; row--, column++)
        if (queens[row] == column) return false;

    return true; // 有效
}

/** 打印一个二维表来显示皇后 */
void printResult(int queens[]){
    // 显示输出
    for (int i = 0; i < N; i++){
        for (int j = 0; j < queens[i]; j++)
            cout << "| ";
        cout << "|Q|";
        for (int j = queens[i] + 1; j < N; j++)
            cout << " |";
        cout << endl;
    }
}

例7.20

·(严格相同数组)如果两个数组 l i s t 1 list1 list1 l i s t 2 list2 list2 具有相同的长度,并且对于每个 i i i 都有 l i s t 1 [ i ] list1[i] list1[i] l i s t 2 [ i ] list2[i] list2[i] 相同,那么称它们严格相同( s t r i c t l y strictly strictly i d e n t i c a l identical identical)。使用下面的函数头编写函数,如果 l i s t 1 list1 list1 l i s t 2 list2 list2 严格相同,那么返回 t r u e true true
bool strictlyEqual ( const int list1[ ], const int list2[ ], int size )
编写测试程序,提示用户输入两个整数数组,并显示它们是否严格相同。

#include<iostream>
using namespace std;

bool strictlyEqual(const int list1[], const int list2[], int size){
    bool flag = true;
    for (int i = 0; i < size; i++){
        if (list1[i] != list2[i]){
            flag = false;
            break;
        }
    }

    return flag;
}

int main(){
    cout << "Enter list1: ";
    int n1;
    cin >> n1;
    const int N1 = n1;
    int list1[N1];
    for (int i = 0; i < N1; i++)
        cin >> list1[i];

    cout << "Enter list2: ";
    int n2;
    cin >> n2;
    const int N2 = n2;
    int list2[N2];
    for (int i = 0; i < N2; i++)
        cin >> list2[i];

    bool isEqual = strictlyEqual(list1, list2, N1);

    if (isEqual)
        cout << "Two lists are strictly identical" << endl;
    else
        cout << "Two lists are not strictly identical" << endl;

    return 0;
}

例7.21

·(模拟:赠券收集问题)赠券收集问题是一个经典的统计问题,具有很多实际应用。这个问题是从对象集合中重复地挑选对象,并判定至少需要多少次挑选才能在某一次挑选中得到全部对象。这个问题有一个变形,从洗乱的52张扑克牌中抽牌,并计算出每种花色都抽到一张至少需要抽多少张牌。假定选完牌之后要放回。编写程序,模拟得到四种花色各一张所需抽牌数量,并显示抽到的这四张牌(同一张牌有可能被抽到两次)。

#include<iostream>
#include<ctime>
#include<string>
#include<cstdlib>
using namespace std;

int main(){
    const int NUMBER_OF_CARDS = 52;
    string suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
    string ranks[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    bool numberOfSpades = false;
    bool numberOfHearts = false;
    bool numberOfDiamonds = false;
    bool numberOfClubs = false;

    srand(time(0));

    int count = 0;
    while (numberOfSpades != true || numberOfHearts != true || numberOfDiamonds != true || numberOfClubs != true){
        int index = rand() % NUMBER_OF_CARDS;
        int x = index / 13;
        int y = index % 13;
        if (x == 0 && numberOfSpades == false){
            numberOfSpades = true;
            cout << ranks[y] << " of " << suits[x] << endl;
        }
        if (x == 1 && numberOfHearts == false){
            numberOfHearts = true;
            cout << ranks[y] << " of " << suits[x] << endl;
        }
        if (x == 2 && numberOfDiamonds == false){
            numberOfDiamonds = true;
            cout << ranks[y] << " of " << suits[x] << endl;
        }
        if (x == 3 && numberOfClubs == false){
            numberOfClubs = true;
            cout << ranks[y] << " of " << suits[x] << endl;
        }
        count++;
    }

    cout << "Number of picks: " << count << endl;

    return 0;
}

例7.22

·(数学:组合)编写程序,提示用户输入10个整数,并显示10个数字中挑选2个数字的所有组合。

#include<iostream>
using namespace std;

int main() {
    int list[10];
    cout << "输入10个整数: "; 
    for (int i = 0; i < 10; i++)
        cin >> list[i];

    int count = 0;
    for (int i = 0; i < 10; i++){
        for (int j = i + 1; j < 10; j++){
            cout << list[i] << list[j] << " ";
            count++;
            if (count % 10 == 0)
                cout << endl;
        }
    }

    return 0;
}

例7.23

·(相同数组)如果两个数组 l i s t 1 list1 list1 l i s t 2 list2 list2 含有相同的内容,那么称它们为相同的( i d e n t i c a l identical identical )。请使用下面的函数头编写函数,如果 l i s t 1 list1 list1 l i s t 2 list2 list2 是相同的,返回 t r u e true true
bool isEqual ( const int list1[ ], const int list2[ ], int size )
编写测试程序,提示用户输入两组整数并显示它们是否是相同的数组。

#include<iostream>
using namespace std;

bool isEqual(const int list1[], const int list2[], int size){
    for (int i = 0; i < size; i++){
        if (list1[i] != list2[i])
            return false;
    }

    return true;
}

void selectionSort(int list[], int listSize){
    for (int i = 0; i < listSize; i++){
        int currentMin = list[i];
        int currentMinIndex = i;

        for (int j = i + 1; j < listSize; j++){
            if (currentMin > list[j]){
                currentMin = list[j];
                currentMinIndex = j;
            }
        }

        if (currentMinIndex != i){
            list[currentMinIndex] = list[i];
            list[i] = currentMin;
        }
    }
}

int main(){
    cout << "Enter list1: ";
    int n1;
    cin >> n1;
    const int N1 = n1;
    int list1[N1];
    for (int i = 0; i < N1; i++)
        cin >> list1[i];

    cout << "Enter list2: ";
    int n2;
    cin >> n2;
    const int N2 = n2;
    int list2[N2];
    for (int i = 0; i < N2; i++)
        cin >> list2[i];

    selectionSort(list1, N1);
    selectionSort(list2, N2);
    
    bool flag = isEqual(list1, list2, N1);

    if (flag)
        cout << "Two lists are identical" << endl;
    else
        cout << "Two lists are not identical" << endl;

    return 0;
}

例7.24

·(模式识别:4个连续的相同数字)编写如下函数,测试数组是否含有4个连续的具有相同值的元素。
bool isConsecutiveFour ( const int values[ ], int size )
编写测试程序,提示用户输入一系列整数,并显示它们是否含有4个连续相同数字。程序应该首先提示用户输入数字的数量,也就是数组的元素数。假定最大的数量是80。

#include<iostream>
using namespace std;

bool isConsecutiveFour(const int values[], int size){
    int value = values[0];
    int count = 1;
    for (int i = 1; i < size; i++){
        if (values[i] == value)
            count++;
        else{
            value = values[i];
            count = 1;
        }

        if (count == 4)
            return true;
    }

    return false;
}

int main(){
    cout << "Enter the number of values: ";
    int n;
    cin >> n;

    cout << "Enter the values: ";
    const int N = n;
    int list[N];
    for (int i = 0; i < N; i++)
        cin >> list[i];

    if (isConsecutiveFour(list, N))
        cout << "The list has consecutive fours" << endl;
    else
        cout << "The list has no consecutive fours" << endl;

    return 0;
}

例7.25

·(游戏:抽4张牌)编写程序,从一副52张牌中抽4张并计算它们的和。A、K、Q、J分别代表1、13、12和11。程序应该显示和为24的选择有多少种。

#include<iostream>
#include<ctime>
#include<string>
#include<cstdlib>
using namespace std;

int main(){
    const int NUMBER_OF_CARDS = 52;
    string suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
    string ranks[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};

    srand(time(0));
    int count = 0;
    for (int i = 0; i < NUMBER_OF_CARDS; i++){
        for (int j = i + 1; j < NUMBER_OF_CARDS; j++){
            for (int k = j + 1; k < NUMBER_OF_CARDS; k++){
                for (int l = k + 1; l < NUMBER_OF_CARDS; l++){
                    if ((i % 13 + 1) + (j % 13 + 1) + (k % 13 + 1) + (l % 13 + 1) == 24){
//                        cout << suits[i / 13] << " of " << ranks[i % 13] << endl;
//                        cout << suits[j / 13] << " of " << ranks[j % 13] << endl;
//                        cout << suits[k / 13] << " of " << ranks[k % 13] << endl;
//                        cout << suits[l / 13] << " of " << ranks[l % 13] << endl;
//                        cout << endl;
                        count++;
                    }
                }
            }
        }
    }
    cout << "和为24的种类有: " << count << endl;

    return 0;
}

例7.26

·(合并两个排列好的数组)编写如下函数,合并两个排列好的数组,形成一个新的排列好的数组。
void merge ( const int list1[ ], int size1, const int list2[ ], int size2, int list3[ ] )
使用 s i z e 1 + s i z e 2 size1+size2 size1+size2 次比较实现函数。编写测试程序,提示用户输入两个排列好的数组,并显示合并以后的数组。

#include<iostream>
using namespace std;

void merge(const int list1[], int size1, const int list2[], int size2, int list3[]){
    int current1 = 0; // Current index in list1
    int current2 = 0; // Current index in list2
    int current3 = 0; // Current index in list3

    while (current1 < size1 && current2 < size2){
        if (list1[current1] < list2[current2])
            list3[current3++] = list1[current1++];
        else
            list3[current3++] = list2[current2++];
    }

    while (current1 < size1)
        list3[current3++] = list1[current1++];

    while (current2 < size2)
        list3[current3++] = list2[current2++];
}

int main(){
    const int MAX_SIZE = 80;

    cout << "Enter list1: ";
    int list1[MAX_SIZE];
    int size1;
    cin >> size1;
    for (int i = 0; i < size1; i++)
        cin >> list1[i];

    cout << "Enter list2: ";
    int list2[MAX_SIZE];
    int size2;
    cin >> size2;
    for (int i = 0; i < size2; i++)
        cin >> list2[i];

    int list3[2 * MAX_SIZE];
    merge(list1, size1, list2, size2, list3);

    cout << "The merged list is ";
    for (int i = 0; i < size1 + size2; i++)
        cout << list3[i] << " ";

    return 0;
}

例7.27

·(排列好了?)编写如下函数,如果数组已经按照升序排列,那么返回 t r u e true true
bool isSorted ( const int list[ ], int size )
编写测试程序,提示用户输入一个数组并显示数组是否是排列好的。

#include<iostream>
using namespace std;

bool isSorted(const int list[], int size){
    for (int i = 0; i < size - 1; i++){
        if (list[i] > list[i + 1])
            return false;
    }

    return true;
}

int main(){
    cout << "Enter list: ";
    int n;
    cin >> n;

    const int N = n;
    int list[N];
    for (int i = 0; i < N; i++)
        cin >> list[i];

    if (isSorted(list, N))
        cout << "The list is already sorted" << endl;
    else
        cout << "The list is not sorted" << endl;

    return 0;
}

例7.28

·(数组的划分)编写如下函数,用数组的第一个元素划分数组,这个元素称为关键点:
int partition ( int list[ ], int size )
划分后,关键点之前的元素都比关键点小或相等,关键点之后的元素都比关键点大。函数同时返回关键点在新数组的位置。

#include<iostream>
using namespace std;

int partition(int list[], int size){
    int first = 0;
    int last = size - 1;
    int pivot = list[first]; // 关键点
    int low = first + 1;
    int high = last;

    while (high > low){
        while (low <= high && list[low] <= pivot)
            low++;
        while (low <= high && list[high] > pivot)
            high--;

        if (high > low){
            int temp = list[high];
            list[high] = list[low];
            list[low] = temp;
        }
    }

    while (high > first && list[high] >= pivot)
        high--;

    if (pivot > list[high]){
        list[first] = list[high];
        list[high] = pivot;
        return high;
    }
    else
        return first;
}

int main(){
    const int MAX_SIZE = 80;

    cout << "Enter list: ";
    int size;
    cin >> size;

    int list[MAX_SIZE];
    for (int i = 0; i < size; i++)
        cin >> list[i];

    partition(list, size);

    cout << "After the partition, the list is ";
    for (int i = 0; i < size; i++)
        cout << list[i] << " ";

    return 0;
}

例7.29

·(多边形面积)编写程序,提示用户输入凸多边形的各顶点,并显示它的面积。假定多边形有六个顶点,且顶点按照顺时针顺序输入。

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

double area(double x1, double y1, double x2, double y2, double x3, double y3){
    double side1 = pow((pow(x2 - x1, 2.0) + pow(y2 - y1, 2.0)), 0.5);
    double side2 = pow((pow(x3 - x1, 2.0) + pow(y3 - y1, 2.0)), 0.5);
    double side3 = pow((pow(x3 - x2, 2.0) + pow(y3 - y2, 2.0)), 0.5);
    double s = (side1 + side2 + side3) / 2.0;
    double area = pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);

    return area;
}

int main(){
    cout << "Enter the coordinates of six points: " << endl;
    double x0, y0, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5;
    cin >> x0 >> y0 >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4 >> x5 >> y5;

    cout << "The total area is " << area(x0, y0, x1, y1, x2, y2) + area(x0, y0, x2, y2, x3, y3)
        + area(x0, y0, x3, y3, x4, y4) + area(x0, y0, x4, y4, x5, y5) << endl;

    return 0;
}

例7.30

·(文化:十二生肖)使用一个字符串数组存储动物的名字,来简化程序清单3-8,ChineseZodiac.cpp。

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

int main(){
    string ChineseZodiac[12] = {"monkey", "rooster", "dog", "pig", "rat", "ox",
                                "tiger", "rabbit", "dragon", "snake", "horse", "sheep"};

    cout << "Enter a year: ";
    int year;
    cin >> year;

    cout << ChineseZodiac[year % 12] << endl;

    return 0;
}

例7.31

·(共有元素)编写程序,提示用户输入两个含有10个元素的整数数组,并显示同时出现在两个数组里的共有元素。

#include<iostream>
using namespace std;

int main(){
    cout << "Enter list1: ";
    int list1[10];
    for (int i = 0; i < 10; i++)
        cin >> list1[i];

    cout << "Enter list2: ";
    int list2[10];
    for (int i = 0; i < 10; i++)
        cin >> list2[i];

    cout << "The common elements are ";
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
            if (list1[i] == list2[j])
                cout << list1[i] << " ";
        }
    }

    return 0;
}

例7.32

·(最长公共前缀)使用如下函数头,重写程序设计练习6-42中的 p r e f i x prefix prefix 函数,来寻找两个C字符串的最长公共前缀。
void prefix ( const char s1[ ], const char s2[ ], char commonPrefix[ ] )
编写测试程序,提示用户输入两个C字符串,并显示它们的公共前缀。

#include<iostream>
#include<cstring>
using namespace std;

void prefix(const char s1[], const char s2[], char commonPrefix[]){
    if (s1[0] != s2[0]){
        cout << s1 << " and " << s2 << " have no common prefix";
        exit(1);
    }

    for (int i = 0; i < min(strlen(s1), strlen(s2)); i++){
        if (s1[i] == s2[i])
            commonPrefix[i] = s1[i];
        else
            break;
    }

    cout << "The common prefix is " << commonPrefix << endl;

    exit(1);
}

int main(){
    cout << "Enter s1:";
    char s1[80];
    cin.getline(s1, 80);

    cout << "Enter s2:";
    char s2[80];
    cin.getline(s2, 80);

    char commonPrefix[80];
    prefix(s1, s2, commonPrefix);

    return 0;
}

例7.33

·(检验子串)重写程序设计练习6.43的 i n d e x O f indexOf indexOf 函数,检验C字符串s1是否是C字符串s2的子串。如果匹配,返回s1在s2中的第一个下标,否则返回-1。
int indexOf ( const char s1[ ], const char s2[ ] )
编写测试程序,读入两个C字符串,检验C字符串s1是否是C字符串s2的子串。

#include<iostream>
#include<cstring>
using namespace std;

int indexOf(const char s1[], const char s2[]){
    int remainingLength = strlen(s2);
    int startingIndex = 0;

    while (strlen(s1) <= remainingLength){

        bool matched = true;
        for (int i = 0; i < strlen(s1); i++){
            if (s1[i] != s2[startingIndex + i]){
                startingIndex++;
                remainingLength--;
                matched = false;
            }
        }

        if (matched) return startingIndex;
    }

    return -1;
}

int main(){
    cout << "Enter the first string: ";
    char s1[80];
    cin.getline(s1, 80);

    cout << "Enter the second string: ";
    char s2[80];
    cin.getline(s2, 80);

    cout << "indexOf(\"" << s1 << "\", \"" << s2 << "\") is " << indexOf(s1, s2) << endl;

    return 0;
}

例7.34

·(指定字符在字符串中出现的次数)使用如下函数头,重写程序设计练习6.44中的 c o u n t count count 函数,找到指定字符在C字符串中出现的次数。
int count ( const char s[ ], char a )
编写测试程序,读入一个字符串和字符,并显示字符在字符串中出现的次数。

#include<iostream>
#include<cstring>
using namespace std;

int count(const char s[], char a){
    int count = 0;

    for (int i = 0; i < strlen(s); i++)
        if (s[i] == a)
            count++;

    return count;
}

int main(){
    cout << "Enter a string:";
    char s[80];
    cin.getline(s, 80);

    cout << "Enter a character:";
    char a;
    cin >> a;

    cout << a << " appears in " << s << " " << count(s, a) << " times" << endl;

    return 0;
}

例7.35

·(字符串中字母的数量)请使用如下函数头编写函数,数出C字符串中的字母数量。
int countLetters ( const char s[ ] )
编写测试程序,读入一个C字符串,并显示字符串中的字母数量。

#include<iostream>
#include<cstring>
#include<cctype>
using namespace std;

int countLetters(const char s[]){
    int count = 0;
    for (int i = 0; i < strlen(s); i++){
        if (isalpha(s[i]))
            count++;
    }

    return count;
}

int main(){
    cout << "Enter a string: ";
    char s[80];
    cin.getline(s, 80);

    cout << "The number of letters in " << s << " is " << countLetters(s) << endl;

    return 0;
}

例7.36

·(互换实例)使用如下函数头重写程序设计练习6.46中的 s w a p C a s e swapCase swapCase 函数,将字符串s1中的大写字母转换成小写,小写字母转换成大写,得到新的字符串s2。
void swapCase ( const char s1[ ], char s2[ ] )
编写测试程序,提示用户输入字符串并调用这个函数,显示新字符串。

#include<iostream>
#include<cctype>
#include<cstring>
using namespace std;

void swapCase(const char s1[], char s2[]){
    int i = 0;
    for( ; i < strlen(s1); i++){
        if (islower(s1[i]))
            s2[i] = toupper(s1[i]);
        else if (isupper(s1[i]))
            s2[i] = tolower(s1[i]);
        else
            s2[i] = s1[i];
    }

    s2[i] = '\0';
}

int main(){
    cout << "Enter a string:";
    char s1[80];
    cin.getline(s1, 80);

    char s2[80];
    swapCase(s1, s2);
    cout << "The new string is:" << s2 << endl;

    return 0;
}

例7.37

·(字符串中每个字母出现的次数)请使用如下函数头编写函数,数出字符串中每个字母出现的次数。
void count ( const char s1[ ], int counts[ ] )
c o u n t s counts counts 是一个有26个元素的整数数组。 c o u n t s [ 0 ] , c o u n t s [ 1 ] , . . . , c o u n t s [ 25 ] counts[0],counts[1],...,counts[25] counts[0],counts[1],...,counts[25] 分别记录 a , b , . . . , z a,b,...,z a,b,...,z 出现的次数。字母不分大小写,例如字母 A A A 和字母 a a a 都被看做 a a a
编写测试程序,读入字符串并调用 c o u n t count count 函数,显示非零的次数。

#include<iostream>
#include<cstring>
#include<cctype>
using namespace std;

void count(const char s[], int counts[]){
    for (int i = 0; i < strlen(s); i++){
        char c = tolower(s[i]);
        if (isalpha(c))
            counts[c - 'a']++;
    }
}

int main(){
    char s[80];
    cout << "Enter a string: ";
    cin.getline(s, 80);

    int counts[26] = {0};

    count(s, counts);

    for (int i = 0; i < 26; i++)
        if (counts[i] > 0)
            cout << (char)('a' + i) << ": " << counts[i] << " times" << endl;

    return 0;
}

例7.38

·(浮点数转换为字符串)请使用如下函数头编写函数,将浮点数转换为C字符串。
void ftoa ( double f, char s[ ] )
编写测试程序,提示用户输入一个浮点数,显示每个数字和小数点,并且用空格隔开。

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

void reverse(char s[]){
    for (int i = 0, j = strlen(s) - 1; i < strlen(s) / 2; i++, j--){
        char temp = s[i];
        s[i] = s[j];
        s[j] = temp;
    }
}

void ftoa(double f, char s[]){
    int count = 0;
    while (abs(f - static_cast<int>(f)) > 0.000001){
        f *= 10;
        count++;
    }

    int value = f;
    int i = 0;
    while (i < count){
        s[i] = value % 10 + '0';
        value /= 10;
        i++;
    }

    s[i++] = '.';
    while (value != 0){
        s[i] = value % 10 + '0';
        value /= 10;
        i++;
    }

    s[i] = '\0';

    reverse(s);
}

int main(){
    char s[80];
    cout << "Enter a number: ";
    double value;
    cin >> value;

    ftoa(value, s);
    cout << "The number is ";
    for (int i = 0; i < strlen(s); i++)
        cout << s[i] << " ";

    return 0;
}

例7.39

·(商业:ISBN-13校验)使用C字符串代替string存储ISBN数字,重写程序设计练习5.51。编写如下函数获得前12位数字的校验和:
int getChecksum ( const char s[ ] )
程序应该按照C字符串读取输入。

#include<iostream>
#include<cstring>
using namespace std;

int getChecksum(const char s[]){
    int temp = 0;
    for (int i = 0; i < 12; i++){
        if (i % 2 == 0)
            temp = temp + static_cast<int>(s[i] - 48);
        else
            temp = temp + 3 * static_cast<int>(s[i] - 48);
    }

    int d13 = 10 - temp % 10;

    return d13;
}

int main(){
    cout << "Enter the first 12 digits of an ISBN-13 as a string:";
    char D[13];
    cin.getline(D, 13);

    if (strlen(D) != 12){
        cout << D << " is an invalid input" << endl;
        return 0;
    }

    if (getChecksum(D) == 10)
        cout << "The ISBN-13 number is " << D << '0' << endl;
    else
        cout << "The ISBN-13 number is " << D << static_cast<char>(getChecksum(D) + 48) << endl;

    return 0;
}

例7.40

·(二进制转换为十六进制)使用如下函数头重写程序设计练习6.38中的 b i n 2 H e x bin2Hex bin2Hex 函数,使用C字符串转换为二进制,返回十六进制。
void bin2Hex ( const char binaryString[ ], char hexString[ ] )
编写测试程序,提示用户输入二进制数字符串,并显示相应的十六进制数字符串。

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

void bin2Hex(const char binaryString[], char hexString[]){
    int decimalValue = 0;

    for (int i = strlen(binaryString) - 1, j = 0; j <= strlen(binaryString) - 1; i--, j++)
        decimalValue = decimalValue + static_cast<int>(binaryString[i] - '0') * pow(2, j);

    itoa(decimalValue, hexString, 16);
}

int main(){
    cout << "输入二进制字符串: ";
    char binaryString[80];
    cin.getline(binaryString, 80);

    char hexString[80];
    bin2Hex(binaryString, hexString);

    cout << "对应的十六进制字符串: " << hexString << endl;

    return 0;
}

例7.41

·(二进制转换为十进制)使用如下函数头重写程序设计练习6.39中的 b i n 2 D e c bin2Dec bin2Dec 函数,转换二进制数字符串,返回十进制数字。
int bin2Dec ( const char binaryString[ ] )
编写测试程序,提示用户输入二进制数字符串,并显示相应的十进制数。

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

int bin2Dec(const char binaryString[]){
    int decimalValue = 0;

    for (int i = strlen(binaryString) - 1, j = 0; j <= strlen(binaryString) - 1; i--, j++)
        decimalValue = decimalValue + static_cast<int>(binaryString[i] - '0') * pow(2, j);

    return decimalValue;
}

int main(){
    cout << "输入二进制字符串: ";
    char binaryString[80];
    cin.getline(binaryString, 80);

    cout << "对应的十进制数: " << bin2Dec(binaryString) << endl;

    return 0;
}

例7.42

·(十进制转换为十六进制)使用如下函数头重写程序设计练习6.40中的 d e c 2 H e x dec2Hex dec2Hex 函数,将十进制数转换为十六进制数字符串。
void dec2Hex ( int value, char hexString[ ] )
编写测试程序,提示用户输入十进制数,并显示相应的十六进制数字符串。

#include<iostream>
using namespace std;

void dec2Hex(int value, char hexString[]){
    itoa(value, hexString, 16);
}

int main(){
    cout << "输入十进制数: ";
    int n;
    cin >> n;

    char hexString[80];
    dec2Hex(n, hexString);

    cout << "对应的十六进制数为: " << hexString << endl;

    return 0;
}

例7.43

·(十进制转换为二进制)使用如下函数头重写程序设计练习6.41中的 d e c 2 B i n dec2Bin dec2Bin 函数,将十进制数转换为二进制数字符串。
void dec2Bin ( int value, char binaryString[ ] )
编写测试程序,提示用户输入十进制数,并显示相应的二进制数字符串。

#include<iostream>
using namespace std;

void dec2Bin(int value, char binaryString[]){
    itoa(value, binaryString, 2);
}

int main(){
    cout << "输入十进制数: ";
    int n;
    cin >> n;

    char binaryString[80];
    dec2Bin(n, binaryString);

    cout << "对应的二进制数为: " << binaryString << endl;

    return 0;
}
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值