问题描述
#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位的)