在c++中打印动态创建的负数会导致不正确的输出
Printing negative numbers created on the fly gives incorrect output in c++
下面的代码解释了一个怪癖,我无法理解为什么它是这样的。代码中的注释解释了这个怪癖:
#include <iostream>
#include <string>
using namespace std;
int main() {
string a,b;
a = "abc";
b = "def";
// On the fly calculation of diff does not lead to desirable results.
cout<<"a size: "<<a.size()<<" b size: "<<b.size()<<" diff: "<<a.size()-b.size()-1<<endl;
// Following assignment works as expected.
int diff = a.size()-b.size()-1;
cout<<"diff "<<diff<<endl;
for (int i=a.size()-1; i>a.size()-b.size()-1; --i) {
cout<<"running"<<endl;
}
return 0;
}
下面是我得到的输出:
a size: 3 b size: 3 diff: 4294967295
diff: -1
a.size()-b.size()-1
由于size
方法返回size_t
,即无符号值,您在"无符号空间"中计算3-3-1 = -1
,这会给您一个错误的值。
试题:
int(a.size())-int(b.size())-1
相关文章:
- 不正确的比较和交换计数器输出用于快速排序功能
- Windows 10命令提示符的输出不正确
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- C++ - 为什么 unicode 输出不正确?
- 连接的组件程序产生不正确的输出
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 我的叉子输出不正确
- 输出使用 cout 转换为 ASCII 的文本时输出格式不正确,C++
- 堆排序,我无法弄清楚我的代码出了什么问题,输出顺序不正确
- C++使用 CEIL 和长度输出不正确的值
- 使用 iconv 进行 UTF8 转换的输出不正确
- C strftime()输出不正确
- 不正确的输出和变量未用Eclipse CDT初始化构造函数
- 当行数和列不匹配时,输出不正确
- 合并排序不正确的输出 c++
- 从堆栈中读取字符后,如何修复不正确的文件输出
- C++ 嵌套循环输出不正确
- 矩阵和矢量乘法,输出不正确的产品
- 我对这个问题有问题,我的输出不正确
- 测试整数是否在范围内时,逻辑错误和不正确输出