You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C++十进制转十六进制程序循环运行直至用户选择终止?

C++十进制转十六进制程序循环执行实现方案

实现逻辑

  • 外层使用do-while循环包裹原有转换代码,确保程序启动后至少完成一次转换操作
  • 每次进入转换流程时重置存储十六进制结果的字符串,避免上一次转换的结果残留
  • 单次转换完成后新增用户选择提示,捕获用户输入的指令判断是否再次执行
  • 当用户输入Y/y时重新进入转换流程,输入其他字符则直接终止程序

优化后完整代码

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    char choice; // 存储用户是否继续的选择
    char hex[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
    do {
        int dec_num, r;
        string hexdec_num = ""; // 每次循环重置结果字符串
        cout << "\n\n Convert a decimal number to hexadecimal number:\n";
        cout << "---------------------------------------------------\n";
        cout << " Input a decimal number: ";
        cin >> dec_num;

        // 补充输入0的特殊处理,避免原代码输出空值
        if (dec_num == 0) {
            hexdec_num = "0";
        }
        while (dec_num > 0)
        {
            r = dec_num % 16;
            hexdec_num = hex[r] + hexdec_num;
            dec_num = dec_num / 16;
        }
        cout << " The hexadecimal number is : " << hexdec_num << "\n";
        
        // 询问用户是否继续
        cout << "\n 是否需要再次执行转换?输入Y/y继续,其他字符退出:";
        cin >> choice;
    } while (choice == 'Y' || choice == 'y'); // 用户输入Y/y时循环执行
    cout << "程序已终止。" << endl;
    return 0;
}

补充说明

原代码未处理输入为0的场景,会直接输出空字符串,上述代码新增了0值的特殊判断,优化了使用体验。

内容的提问来源于stack exchange,提问作者Darin Hinze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:09:03