新手小白求教循环判断异常处理
本帖最后由 sundeam 于 2023-11-17 09:52 编辑各位大佬,我是c++菜鸟,今天遇到一个循环判断的问题,一直找不到原因,求指教。
#include<iostream>
#include <limits>
#include<random>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
intnum = 0; int a = 0; int b = 100; int c = 0; time_t t;
srand((unsigned)time(&t));
num = rand()%100;
for (;;)
{
cout << "请输入" << a << "---" << b << "之间任意一个数值";
cin >> c;
if (num==c)
{
cout << "恭喜你答对了~!" << endl;
a = 0; b = 100;
num = rand() % 100;
}
if (num>c>a)
{
a = c;
}
if (b>c>num)
{
b = c;
}
}
每次循环到if (num>c>a)可以正常判断,执行完一次后,后面输入的数据就不判断了?
经过大佬的分享,完美解决判断异常问题,谢谢~!
下面附上修改后的
using namespace std;
int main()
{
intnum = 0; int a = 0; int b = 100; int c = 0; time_t t;
srand((unsigned)time(&t));
num = rand()%100;
for (;;)
{
cout << "请输入" << a << "---" << b << "之间任意一个数值";
cin >> c;
if (num==c)
{
cout << "恭喜你答对了~!" << endl;
a = 0; b = 100; c = 0;
num = rand() % 100;
}
if (c < 0 && c>100)
{
cout << "你输入的数值超出范围,请重新输入:" << endl;
c = 0;
}
if (num>c && c>a)
{
a = c;
}
if (b>c && c>num)
{
b = c;
}
} c/c++语言没有连续大于这种写法,正确写法应该是num > c && c > a,b > c && c > num,在 c/c++ 中,符号 “>” 是一种用于比较两个值的运算符,它的含义是“大于”。该运算符用于比较两个操作数的大小关系,如果左操作数大于右操作数,则返回真(1),否则返回假(0)。 The given code snippet is a loop that continuously asks the user to enter a number between variables a and b. The loop will continue running until the user enters the correct number, indicated by if (num == c).
If the user guesses the correct number, a message "恭喜你答对了~!" will be displayed. Then, variables a and b are reset to 0 and 100 respectively, and a new random number is generated using num = rand() % 100.
If the user's guess is less than the correct number, the lower limit of the range, a, is updated to the guessed number using a = c.
If the user's guess is greater than the correct number, the upper limit of the range, b, is updated to the guessed number using b = c.
The loop will continue with the updated range until the correct number is guessed. 楼上正解
c/c++语言没有连续大于这种写法,,改成相应的写法即可 无问且问 发表于 2023-11-16 18:14
c/c++语言没有连续大于这种写法,正确写法应该是num > c && c > a,b > c && c > num,在 c/c++ 中,符号 “ ...
这样的写法编译之后会怎么运行啊,lz的程序过编译了 判断写错了,不能这样判断 不能这样判断,应该是 判断有错误得修改一下 这种连续大于或小于我只在python里写过,c/c++是没有这种写法的。这样写实际上相当于(a>b)>c,可以看看下面的输出:
std::cout << (4 > 3 > 2) << "" << (4 > 3 > -1) << std::endl;
页:
[1]
2