【问题标题】:Xcode C++ Errors preventing further output past srand()Xcode C++ 错误阻止进一步输出超过 srand()
【发布时间】:2016-07-13 16:38:26
【问题描述】:

我正在开发一个程序,该程序生成两个随机数和一个 if 语句,该语句生成“+”表示加法或“-”表示减法。我目前无法检查并查看我的 putput 是什么,因此我可以更正任何错误,因为程序运行我的开头“欢迎”语句,然后显示在蓝色括号 (lldb) 中并且代码停在那里。我注意到在我的 srand(time(0)) 函数旁边它变成绿色并显示“线程 1:断点 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;

}

【问题讨论】:

  • 与您的问题无关,但O 的值将始终相同,因为您在初始化随机数生成器之前生成了它。编辑:您的代码似乎在ideone 上编译得很好。
  • 请不要使用'O'作为变量名。它看起来太像“0”了。

标签: c++ xcode random time


【解决方案1】:

time(0) 返回一个time_t 类型的值,这显然是您机器上的long

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

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

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

【讨论】:

  • 谢谢博!这摆脱了错误,但它给我带来了另一个错误。我现在得到一个从 if(O == 2) 语句开始的语句,它读取线程 1:断点 1.1
猜你喜欢
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多