第二十三篇 -- 研究下函数(六)—— 综合实例

两个实例

一、判断素数

// IsPrimeNumber.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"
#include <iostream>
using namespace std;

#include <cmath>

bool IsPrimeNumber(int num);

int main()
{
    cout << "——判断是否是素数——" << endl; 
    int num = 0;
    cout << "请输入一个正整数:" << endl;
    cin >> num;
    while (num > 0) {
        if (IsPrimeNumber(num)) {
            cout << num << "是一个素数" << endl;
        }
        else {
            cout << num << "不是一个素数" << endl;
        }
        cout << endl << "请输入一个正整数:" << endl;
        cin >> num;
        if (num == 0) {
            break;
        }
    }

    return 0;
}

bool IsPrimeNumber(int num) {
    if (1 == num || 2 == num) {
        return true;
    }

    int s = static_cast<int>(sqrt(num));          //求平方根
    for (int i = 2; i <= s; i++) {//从2开始遍历,直到平方根
        if ((num % i) == 0) {        //如果可以整除,则不是素数
            return false;
        }
    }
    return true;
}

加了一个输入0就退出循环的条件。

二、分割字符串

#include "pch.h"
#include <iostream>
using namespace std;

#include <assert.h> 

int SplitString(char *dest,
    char token,
    char *str1,
    char *str2);

int main()
{
    cout << "——分割字符串——" << endl;    //输出提示信息

    const int LEN = 16;       //字符串长度变量

    cout << "请输入字符串:" << endl;
    char dest[LEN] = { '' };  //初始化目标字符串
    cin >> dest;                //输入目标字符串

    cout << "请输入一个分解字符:" << endl;
    char token = ' ';       //分界字符变量
    cin >> token;           //输入分界字符
    cout << endl;

    char str1[LEN] = { '' };       //初始化字符串
    char str2[LEN] = { '' };

    int index = SplitString(dest, token, str1, str2);    //调用分割字符串的函数
    cout << "字符串在位置" << index << "分割成两个字符串: " << endl;
    cout << str1 << '	' << str2 << endl;

    return 0;
}

int SplitString(char *dest, //目标字符串
    char token,     //分界字符
    char *str1,     //分界字符前的字符串
    char *str2)     //分界字符后的字符串
{
    assert(dest);        //检验参数的有效性
    assert(str1);
    assert(str2);

    int index = 0;     //保存分界位置的变量
    bool befToken = true;     //是否在标志前
    while (*dest != '') {    //遍历整个目标字符串
        if (*dest != token) {    //如果当前字符不是分界字符
            if (befToken) {      //如果在分界字符前
                index++;        //分界位置加1
                *(str1++) = *(dest++);      //保存分界字符前的字符串
            }
            else {
                *(str2++) = *(dest++);      //保存分界字符后的字符串
            }
        }
        else {
            befToken = false;           //跨越了分界字符
            dest++;                     //处理下一个字符
        }
    }
    *str1 = '';        //标识字符串的结尾
    *str2 = '';
    return index;
}

关于assert检验参数的合法性这一块,还是需要注意的。频繁的使用会影响程序的性能。http://www.169it.com/article/11369597425660380263.html

原文地址:https://www.cnblogs.com/smart-zihan/p/11344839.html