C++求素数

C++ continue语句求100-200之间的素数

#include <iostream>

int main() {
    for (int num = 100; num <= 200; num++) {
        bool isPrime = true;
        
        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                isPrime = false;
                break; // 跳出当前循环
            }
        }

        if (isPrime) {
            std::cout << num << " 是素数\n";
        }
    }

    return 0;
}

C++中的continue语句用于跳过当前循环中剩余的代码并开始下一次循环。在上述示例中,我们使用了两个嵌套的for循环来找出100到200之间的所有素数。

当一个数不是素数时,通过break语句跳出内部循环;而当一个数是素数时,则会输出该素数。

C++函数概述翻译密码

#include <iostream>
#include <string>

std::string encrypt(const std::string& plaintext, int shift) {
    std::string ciphertext = "";
    for (char c : plaintext) {
        if (isalpha(c)) {
            char base = isupper(c) ? 'A' : 'a';
            ciphertext += static_cast<char>((c - base + shift) % 26 + base);
        } else {
            ciphertext += c;
        }
    }
    return ciphertext;
}

int main() {
    std::string message = "Hello, World!";
    int shift = 5;
    std::string encryptedMessage = encrypt(message, shift);
    std::cout << "Encrypted message: " << encryptedMessage << std::endl;
    
    return 0;
}

在上述示例中,我们定义了一个名为encrypt的函数来进行简单的凯撒密码加密。该函数接受一个明文字符串和一个整数偏移量作为参数,并返回加密后的字符串。

main函数中,我们调用encrypt函数对消息进行加密,并输出加密后的结果。C++中的函数用于封装可重复使用的代码块。函数由函数头、函数体和返回语句组成。

在函数头中,我们指定了函数的返回类型、函数名以及参数列表。在函数体中,我们编写实际的功能代码。在示例中,encrypt函数的返回类型为std::string,接受一个const std::string&类型的参数和一个int类型的参数。

  • 24
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值