如何在c++中使用int值创建循环(简单)

How can I create loop using int value in c++ (simple)

本文关键字:创建 循环 简单 int c++      更新时间:2023-10-16

我有一个整数值,例如5794。我想在每个数字上应用几个计算而不使用数组

int encrypt;
cout << "Enter 4 digit numbers to encryption :> ";
cin >> encrypt;
for(int i=1;i<=encrypt;i++){
   cout << encrypt  << endl;
}

这段代码打印整个数字,但是我想打印每个数字而不使用数组。如果号码是5794,我想显示:

5
7
9
4

我不希望它像这样显示:

5794

提示:使用modulus(%)和division(/)运算符

如果给定的数字有四个digit,则将其除以1000,100,10,1:

std::cout << "n" << encrypt/1000%10;
std::cout << "n" << encrypt/100%10;

好吧,如果你有数字5794,你需要从数学上提取这些数字。

提示:如果将数字除以1000会发生什么?

扫描数字,然后可以使用整数除法和提醒(%)运算符提取每个数字

这是你想要的吗?:

// get the number from stdin, std::cin >> v; 
visitNumber(int v)
{
    int v1 = v;
    size_t len = 0;
    while(v1){
        v1 /= 10;    
        ++ len;
    }
    for(int i=len; i>0; --i){
        std::cout << (v/pow(10,i)) << std:endl; // or some other op you favorate
    }
}

既然你有麻烦把其他回复者的建议写进代码:

int divisor = 1000;
std::cout << "enCRAPtion digits:n";
for (unsigned int j = 0; j < 3; ++j)
{
    cout << (encrypt / divisor) << "nn";
    encrypt = encrypt % divisor;
    divisor = divisor / 10;
}

顺便说一下,这个词是"加密"而不是"加密"。