如果变量C++为真或假

if cin true or false from variable C++

本文关键字:变量 C++ 如果      更新时间:2023-10-16

请帮我解决这个问题。

int A=10;
cout<<"Answer this Question!";
cout<<"5 + 5 = ";cin>>A;
if(true) {
    cout<<"Correct!"<<endl;
} else if (false) {
    cout<<"Wrong!"<<endl;
}
getch();
}

的答案是A=10,如果用户从int A=10输入正确的答案,则通知使用cout"正确!",如果错误是"错误!".

在上面的代码中,

如果(真的)

总是求值为true,所以它总是输出"Correct!"然而,我猜你是在问我们如何检查用户的输入,看看他们是否正确?在这种情况下,对于if语句,您需要

if (A == 10)

而不是else if,因为除了10以外的任何答案都是不正确的。

我建议你查一下编程基础知识。

您可以使用两个独立的变量,一个用于用户的答案,另一个用于正确答案,然后比较它们:

int correctAnswer = 10;
int userAnswer = 0;
cout << "Answer this Question!";
cout << "5 + 5 = ";
cin >> userAnswer;
if (correctAnswer == userAnswer) {
    cout << "Correct!" << endl;
} else {
    cout << "Wrong!" << endl;
}
getch();
int main(){
  int A = 0;
  std::cout<<"Answer this question: 5 + 5 = "; 
  std::cin>>A;
  if(A == 10){
    std::cout<<"Correct"<<std::endl;
  }else{
    std::cout<<"Wrong"<<std::endl;
  }
  return 0;
}

使用如下代码:)

//...
int B;
cin>>B;
if( A == B ) {
    cout<<"Correct!"<<endl;
} else {
    cout<<"Wrong!"<<endl;
}