C++ 取模返回不一致的结果

问题描述 投票:0回答:1

有人可以告诉我为什么这两个函数返回不同的结果吗?

运行代码后

#include <string>
#include <stdio.h>
#include <iostream>
using namespace std;

int returnN(string s, int n)
{
    int newN = n % s.size();
    return newN;
}

int returnN2(string s, int n)
{
    int a = s.size();
    int newN = n % a;
    return newN;
}

int main(void)
{
    string text2 = "Hello World!";
    cout << returnN(text2, -2) << endl;
    string text3 = "Hello World!";
    cout << returnN2(text3, -2) << endl;
}

returnN(text2, -2) 返回 2

returnN2(text3, -2) 返回 -2

PS D:\src\cpp> g++ --version
g++.exe (Rev3, Built by MSYS2 project) 13.2.0
Copyright (C) 2023 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

我尝试调试并查看原因,但我仍然无法弄清楚为什么

c++ modulo
1个回答
0
投票

s.size()
返回无符号的
size_t

因此,

returnN
returnN2
之间的区别在于用于模计算的操作数的类型

  1. returnN
    中,您使用无符号值执行取模 (
    s.size()
    )。
  2. returnN2
    中,您首先将
    s.size()
    分配给
    a
    进行签名,然后使用带符号的值执行模运算。

你的编译器应该提醒你这个问题。
例如,MSVC 会针对初始化发出以下警告

a

warning C4267: 'initializing': conversion from 'size_t' to 'int', possible loss of data
© www.soinside.com 2019 - 2024. All rights reserved.