c++ - C++ 随机 srand 代码 - 如果 else 不给出正确的结果
问题描述
我没有收到对我的代码的正确响应。当我输入正确的数字时,它应该给出“优秀”;但是,它总是输出“不正确” - 请提出建议。
#include <iostream>
#include <ctime>
using namespace std;
int guess()
{
int x = 0;
x = 1 + rand() % 1000;
return x;
}
int main()
{
int input = 0;
srand( time( 0 ) );
cout << guess() << endl;
cout << "I have a number between 1 and 1000. " << endl;
cout << "Can you guess my number? " << endl;
cout << "Please type your first guess. " << endl;
cin >> input;
if (guess() == input)
cout << "Excellent! You guessed the number! " << endl;
else
cout << "Incorrect! " << endl;
system ("pause");
return 0;
}
解决方案
您调用了两次 function guess()
,因此每次运行时它可能会为您提供不同的值。您必须存储该值,然后将其与原始值进行比较。
推荐阅读
- json - 如何在python石墨烯解析器中返回json,引号前没有反斜杠
- android - Gradle 抱怨错误的 Android 支持库版本
- javascript - categorise an element in Array for loop javascript
- linux - 以更多内存限制运行 PyCharm
- javascript - How to stop applying both required scss and ng-invalid class scss in angular md2 input textarea control
- c - 从 C 中的文本文件中查找并保存整数
- sql - SQL 在 ID 列表中选择顶部 parentId,如果所有顶部 parentId 相同,则返回行
- sapui5 - 将自定义 SAPUI5 库添加到 SAP Cloud Platform Fiori Launchpad(门户服务)
- php - 我的 Php 页面在移动设备中只呈现一半和完整
- javascript - ui5 sap.m.PDFViewer - 嵌入式工具栏