C++ "if"循环中的循环错误

C++ Loop error in 'if' loop

本文关键字:循环 错误 C++ if      更新时间:2023-10-16

我的代码生成了一个异常。

X = x * 10;
Y = y * 10;
if ((pow(X, 2))+(pow(Y, 2)) <= 27225 and ((pow(X, 2))+(pow(Y, 2)) >= 1225))

用户将输入xy的值,如果值不低,程序将继续。我在上面声明x和y是双精度。这部分上面有代码,不是开始。

我把这个代码作为我的另一个if函数

if (((pow(X, 2))+(pow(Y, 2)) > 27225) or ((pow(X, 2))+(pow(Y, 2)) <1225))
{
      cout<<"nnThe values you have chosen for the centre points are to not compatible with our program. Please choose smaller values.";//new
      cout<<"nnIf you do not understand, please ask the programmer for further explanation.";
}

然而,我不能让代码工作,因为没有施加限制,它只是继续正常运行,即使值太大/小,有人能告诉我我做错了什么吗?由于

我认为你的第一个if条件应该检查它是否大于1225且小于27225:

if ((pow(X, 2))+(pow(Y, 2)) <= 27225 && ((pow(X, 2))+(pow(Y, 2)) >= 1225))
//                              Here ^^

正如你所知道的,XY的每一个可能值都满足这个条件;每个数字要么小于27225要么大于1225。

对于第二个条件,只需执行else:

if ((pow(X, 2))+(pow(Y, 2)) <= 27225 && ((pow(X, 2))+(pow(Y, 2)) >= 1225)) {
  // Distance from origin is within range
} else {
  // Distance from origin is outside range
}

注意orand不常用,因为它们是||&&的替代标记。为了与大多数其他开发人员保持一致,我建议坚持使用||&&

从您的代码来看,您似乎没有定义X, Y的数据类型。而不是

X = x * 10;
Y = y * 10;

请尝试

 int X = x * 10;
 intY = y * 10;

if (((pow(X, 2))+(pow(Y, 2)) > 27225)) {
  cout<<"nnThe values you have chosen for the centre points are to not  compatible   with our program. Please choose smaller values.";//new
}
else if( ((pow(X, 2))+(pow(Y, 2)) <1225))
{
        cout<<"nnIf you do not understand, please ask the programmer for further  explanation.";
}

这将为您提供预期的两个不同的结果