Xcode C ++错误阻止进一步输出srand()

时间:2016-07-13 16:38:26

标签: c++ xcode random time

我正在研究一个生成两个随机数的程序和一个if语句,它生成一个“+”表示加法或“ - ”表示减法。我目前无法检查并查看我的putput是什么,所以我可以纠正任何错误,因为程序运行我的开始“欢迎”语句然后显示在蓝色括号(lldb),代码停在那里。我注意到在我的srand(time(0))函数旁边它变为绿色并且说“thread 1:breakpoint 1.1”并在其下面读取“隐式转换失去整数精度:'time_t'(又名'long')到'unsigned int “”。有没有办法解决这些问题或让错误消失?我的代码如下。任何帮助或见解将不胜感激,谢谢!

#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;

int main()

{
    cout << "Welcome to the Math Tutor!" << endl;

    int N1, N2;
    int O = rand() % 2;
    int Result;
    int Answer;

    srand(time(0));

    if(O == 2)
    {
        cout << "+";
    }

    else
    {
        cout << "-";
    }

    N1 = 100 + rand() % 999;
    N2 = 100 + rand() % 999;
    Result = N1 + O + N2;

    cout << setw(10) << N1 << endl;
    cout << setw(10) << N2 << O << "\n";
    cout << setw(10) << "------\n\n";

    cout << "Enter your answer: ";
    cin >> Answer;

    if(Answer == Result)
    {
        cout << "You are correct!\n\n";
    }

    else
    {
        cout << "You are incorrect, the correct answer is: " << Result << "\n\n";
    }

    cin.ignore(1);
    return 0;

}

1 个答案:

答案 0 :(得分:1)

time(0)会返回time_t类型的值,显然是您计算机上的long

当您将此long传递给srand()时,期待unsigned int,并非long的所有值都适合unsigned int。你可以通过使用强制转换来告诉编译器你不关心这个问题。

srand(static_cast<unsigned int>(time(0))); 

当你寻找一些或多或少的随机数时,在这种情况下,精度的损失并不重要。