使用do–while循环执行用户想要的多次操作

时间:2020-03-22 14:59:07

标签: c++

我正在用C ++开发一个程序,该程序可以计算给定数字的阶乘。使用for循环来计算阶乘&do–while循环以根据用户需要执行多次操作

我用for循环为阶乘编写了一个代码,但是无法使用Do while循环执行 代码如下

int n;
int factorial = 1;

cout << "Enter a positive integer: ";
cin >> n;

for(int i = 1; i <=n; ++i)
{
     factorial *= i;   // factorial = factorial * i;
}

cout << "Factorial of " << n << " = " << factorial;    

请帮助我。

2 个答案:

答案 0 :(得分:2)

尝试这个:

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

int main()
{
    string answer;

    do {
        int n;
        int factorial = 1;

        cout << "Enter a positive integer: ";
        cin >> n;

        for(int i = 1; i <=n; ++i)
        {
            factorial *= i;   // factorial = factorial * i;
        }

        cout << "Factorial of " << n << " = " << factorial << endl;

        cout << "Would you like to do again? (type 'n' for No, anything for yes)"  << endl;
        cin >> answer;
        cin.clear(); // Clearing the cin buffer

    } while (answer != "n");

    cout << "Exitting"  << endl;


    return 0;
}

更新(根据评论中的请求)

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

int main()
{
    int counter=0, amount;

    cout << "How many times : ";
    cin>> amount;

    do {
        int n;
        int factorial = 1;

        cout << "Enter a positive integer: ";
        cin >> n;

        for(int i = 1; i <=n; ++i)
        {
            factorial *= i;   // factorial = factorial * i;
        }

        cout << "Factorial of " << n << " = " << factorial << endl;

        counter++;

    } while (counter < amount);

    cout << "Completed"  << endl;

    return 0;
}

答案 1 :(得分:0)

这是使用do-while循环的逻辑。

import tensorflow as tf

input_mask = tf.keras.layers.Input((2, 2, 3))
repeated = tf.keras.layers.Lambda(
    lambda x: tf.keras.backend.repeat_elements(x=x, rep=512, axis=3))(input_mask)
model =tf.keras.models.Model(inputs=input_mask, outputs=repeated)
相关问题