簡體   English   中英

嘗試在 c++ 中創建隨機數生成器並出現錯誤

[英]Trying to create a random number generator in c++ and getting an error

我對 c++ 很陌生,目前正在嘗試從頭開始編寫隨機數生成器。 但是,我在 while 語句下遇到錯誤,我不知道我做錯了什么。 我在 python 方面有一些經驗,所以也許我想我可能會創建類似 python 的語法而不是 c++ 一個? 謝謝你。

#include <iostream>
using namespace std;


class Random {
public:
    double oldRoot;
    double newRoot;
    int iteNum;

    Random(double aOldRoot, double aNewRoot, int aIteNum) {
        oldRoot = aOldRoot;
        newRoot = aNewRoot;
        iteNum = aIteNum;
    }

    int count = 0;

    while (count <= iteNum) {
        double totalRoot;
        totalRoot = oldRoot + newRoot;
        if totalRoot > 1.0{
            oldRoot = newRoot;
            newRoot = totalRoot - 1.0;
        }
        else {
            oldRoot = newRoot;
            newRoot = totalRoot;
        }
        cout << oldRoot << endl;
        cout << newRoot << endl;

        count += 1
    }

};

int main() {

    Random random10(0.1412, 0.2343, 10);

    return 0;

}

問題是您的生成器代碼不在 class 的方法中,它在 class 聲明本身中,這是語法錯誤。 嘗試更多類似的東西:

#include <iostream>
using namespace std;


class Random {
public:
    double oldRoot;
    double newRoot;
    int iteNum;

    Random(double aOldRoot, double aNewRoot, int aIteNum) {
        oldRoot = aOldRoot;
        newRoot = aNewRoot;
        iteNum = aIteNum;
    }

    void generate() {
        int count = 0;

        while (count <= iteNum) {
            double totalRoot = oldRoot + newRoot;
            if (totalRoot > 1.0) {
                oldRoot = newRoot;
                newRoot = totalRoot - 1.0;
            }
            else {
                oldRoot = newRoot;
                newRoot = totalRoot;
            }
            cout << oldRoot << endl;
            cout << newRoot << endl;

            count += 1;
        }
    }
};

int main() {

    Random random10(0.1412, 0.2343, 10);
    random10.generate();

    return 0;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM