首页 > 解决方案 > 如果任何大于 10 或小于 10 的数字会说“错误答案”,我将如何做到这一点?

问题描述

我正在尝试编写代码,所以如果答案少于 10 或多于 10,它会说“错误答案”我现在只是测试一些东西我对编码很陌生。现在我有:

#include <iostream>
#include "log.h"

int main()
{
    MultiplyAndLog2(5, 2); // this is what is going to be multiplied
    
    int x = 11;

    if (x == 10) // I have it so I if it equal to 10 it says right answer
        Log("right answer");
    
    if (x == )  // Heres where im stuck I dont know what to add if any number other than 10 is the answer
        Log("wrong answer");    
    
    std::cin.get();
}

这是我的 log.h 有点乱...

#pragma once

int Multiply(int a, int b, int c) // this is so I can multiply 3 integers at a time just for testing.
        {
            return a * b * c;
        }

int Multiply(int a, int b) // this is the same thing but for 2 integers at a time
{
    return a * b;
}

void MultiplyAndLog(int a, int b, int c) // this is so that whatever 3 integers are multiplied it would say answer: and then the answer to the question
{
    int result = Multiply(a, b, c);
    std::cout << "answer:" << result << std::endl;
}

void MultiplyAndLog2(int a, int b) // this is so that is 2 integers are multiplied it would say answer: and then the answer to the question
{
    int result = Multiply(a, b);
    std::cout << "answer:" << result << std::endl;
}

void Log(const char* message)  // This is so if I type Log I can write whatever I want for example "right answer"
{
    std::cout << message << std::endl;
}

谢谢你,马里奥

标签: c++if-statement

解决方案


您可以使用!=运算符来检查两个值是否不相等:

if (x != 10)
    Log("wrong answer");

另一种方法是使用!运算符来否定逻辑:

if (!(x == 10))
    Log("wrong answer");

也可以直接编码“如果答案小于 10 或大于 10”:

if (x < 10 || x > 10)
    Log("wrong answer");

或者更好的方法:

if (x == 10) {
    Log("right answer");
} else {
    Log("wrong answer");
}

推荐阅读