C ++问题中的sqrt函数

问题描述

#include <iostream>
#include <cmath>

using namespace std;

int main(){
    
    int n;
    cin >> n;
    
    int i = sqrt(1 + 2 * n * (n + 1)) - 1;
    
    cout << i;
}

我编写了一个简单的程序,该程序利用C ++中的sqrt()函数。即使sqrt()的输入为正,上述程序也会在控制台上打印n = 32768的负值。我尝试将语句从int i = sqrt(1 + 2 * n * (n + 1)) - 1;更改为
double i = sqrt(1 + 2 * n * (n + 1)) - 1;,但错误无法解决。

输出:

32768
-2147483648

上面的输出用于int i = sqrt(1 + 2 * n * (n + 1)) - 1;

请帮助!

解决方法

<ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fillViewport="true" android:scrollbars="none"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:minLines="1" android:paddingLeft="5dp" android:paddingTop="11dp" android:paddingRight="70dp" android:paddingBottom="90dp" android:gravity="top|start" android:scrollHorizontally="false" android:background="@android:color/transparent" android:maxLength="999999" android:maxLines="999999" android:inputType="textMultiLine|textVisiblePassword|textNoSuggestions" android:textSize="14dp" /> </LinearLayout> </ScrollView> 更改为int n。您的计算double n溢出了1 + 2 * n * (n + 1)的范围,该范围对于32位是-2,147,483,648到2,647。

旁注:int可能不是32位的,取决于平台(但是,通常大多数情况下是32位的)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...