reactjs - 为什么 React 中的排列计算器会得到荒谬的结果?

标签 reactjs react-hooks permutation use-effect use-state

我有一个用于查找排列的计算器: 当 r 的值超过 n 时,它会显示一条警报消息。当 r 小于或等于 n 时,它应该给出准确的结果。但它的行为很荒谬。 我在 React.js 中编写的相同代码:

 const PnC = () => {
    const [n, setN] = useState(null);
    const [r, setR] = useState(null);
    const [choice, setChoice] = useState("Permutation");
    const [choiceData, setChoiceData] = useState({
      name: "Permutation",
    });
    const [result, setResult] = useState(null);
    useEffect(() => {
      if (choice == "Permutation")
        setChoiceData({ name:"Permutation" });
      else
        setChoiceData({ name:"Combination" });
    }, [choice]);
    const handleChange = (e) => {
      reset();
      setChoice(e.target.value);
    }
    function reset() {
      setN(null);
      setR(null);
      setResult(null);
    }
    function factorial(x){
      var result = 1;
      for (let i = 1; i <= x; i++)
        result *= i;
      return result;
    }
    const calcResult = () => {
      console.log(n,r);
      if (choice == "Permutation") {
        if (n < r)
          alert("The value of n should not be less than r.Please enter valid values for n and r");
        else
          setResult(factorial(n) / factorial(n - r));
      }
      else  if(choice=="Combination"){
        if (n < r)
          alert("The value of n should not be less than r.Please enter valid values for n and r");
        else
          setResult(factorial(n) / (factorial(r) * factorial(n - r)));
      }

    }
    return (
      <>
        <Form>
          <Form.Group className="mb-4" controlId="choice">
            <Form.Label>Select the type of calculation</Form.Label>
            <Form.Control
              as="select"
              className="select-custom-res"
              onChange={(e) => handleChange(e)}
            >
              <option value="Permutation">Permutation</option>
              <option value="Combination">Combination</option>
            </Form.Control>
          </Form.Group>
          <Form.Group className="mb-4" controlId="text">
            <Form.Text className="text">
              <strong>
                To find the {choiceData.name}, Enter the following values
              </strong>
              <br />
            </Form.Text>
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Label>Value of N</Form.Label>
            <Form.Control
              onChange={(e) => setN(e.target.value)}
              type="number"
              placeholder={"Enter the value of n"}
              value={n === null ? "" : n}
            />
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Label>Value of R</Form.Label>
            <Form.Control
              onChange={(e) => setR(e.target.value)}
              type="number"
              placeholder={"Enter the value of r"}
              value={r === null ? "" : r}
            />
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Control
              readOnly
              type="number"
              placeholder={result === null ? "Result" : result + " "}
            />
          </Form.Group>
        </Form>
        <div className="button-custom-grp">
          <Button variant="primary" onClick={calcResult}>
            Calculate
          </Button>
          &nbsp;&nbsp;&nbsp;
          <Button variant="dark" onClick={() => reset()} type="reset">
            Reset
          </Button>
        </div>
      </>
    )
  }

对于像 n=8,r=2 这样的值,我得到了预期的结果,但是对于像 n=13,r=2 这样的值,我得到了自定义警报message n 的值不应小于 r。请输入 n 和 r 的有效值。组合计算器也是如此。为什么我会得到如此荒谬的结果?

最佳答案

问题

n的类型和r从输入更新后是字符串类型,而不是数字。除非您尝试与它们进行数值比较,否则这不是问题。

if (n < r)

此时,是一个字符串逐位置比较。

console.log('"8" < "2"', "8" < "2");   // false
console.log('"13" < "2"', "13" < "2"); // true

"1"字符代码小于 "2"所以比较"13" < "2"评估为真。

解决方案

转换 nr更新状态时改为数字类型。

<Form.Group className="mb-4">
  <Form.Label>Value of N</Form.Label>
  <Form.Control
    onChange={(e) => setN(Number(e.target.value))} // <-- convert to number
    type="number"
    placeholder={"Enter the value of n"}
    value={n === null ? "" : n}
  />
</Form.Group>
<Form.Group className="mb-4">
  <Form.Label>Value of R</Form.Label>
  <Form.Control
    onChange={(e) => setR(Number(e.target.value))} // <-- convert to number
    type="number"
    placeholder={"Enter the value of r"}
    value={r === null ? "" : r}
  />
</Form.Group>

Edit why-getting-absurd-result-on-permutation-caluclator-in-react

关于reactjs - 为什么 React 中的排列计算器会得到荒谬的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71136090/

相关文章:

c - 该算法在 Big-O 表示法(字符串排列)中的顺序是什么?

javascript - Jest 测试文件中的模拟文档

ReactJS 通过 ref 渲染元素

javascript - React Hook "useState"在函数 "setResults"中调用,该函数既不是 React 函数组件也不是自定义 React Hook 函数

javascript - React useReducer 查找和更改状态中的单个对象

javascript - 正则表达式匹配一组中的 1 个或两个字符,并确保它们不同

javascript - React 中的简单轮播 - 如何注册滚动到下一张幻灯片?

javascript - 在 React 中构建 360 度图像的简单组件

reactjs - Firebase 身份验证和 React Hook - 从钩子(Hook)返回的函数不起作用

matlab - 检索特定排列而不在 Matlab 中存储所有可能的排列