当前位置:网站首页>编写程序,计算2/1+3/2+5/3+8/5.....的值。要求计算前n项之和,保留2位小数(该序列从第二项起,每一项的分子是前一项分子与分母的和,分母是前一项的分子)
编写程序,计算2/1+3/2+5/3+8/5.....的值。要求计算前n项之和,保留2位小数(该序列从第二项起,每一项的分子是前一项分子与分母的和,分母是前一项的分子)
2022-06-10 12:28:00 【不爱健身的数学子弟不是好程序员】

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
public class test03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你想计算的前几项和");
int n = sc.nextInt();
double sum = 0;
double temp = 0; //作为一个中间数来交换赋值
double x = 2, y = 1;
for (int i = 1; i <= n; i++) {
sum += x / y;
temp = x;
x = x + y;
y = temp;
}
NumberFormat d = new DecimalFormat(".##"); //格式化数字,保留小数点后两位
String format = d.format(sum);
System.out.println("前" + n + "项和为" + format);
}
}
结果:


边栏推荐
- Learning of cc2642r Bluetooth MCU chip
- Traversing object properties of unknown type
- (7) Deep and shallow copy
- Shadergraph - 302 swimming Dragon
- VDMA调试总结
- [Yan Xuan], real problem analysis
- 已拿offer,进阶学习
- Use of indexeddb database
- JS array de duplication: de duplication of two-dimensional arrays, removal of the same value, and removal of the same array
- Is it safe to open an account in qiniu
猜你喜欢

STM32F407学习笔记(1)-EXTI中断事件与NVIC寄存器

ShaderGraph——水晶

Web development

JS translates Arabic numerals into Chinese capital figures, JS converts figures into capital amounts (sorting)

Driver. JS - open source and independent interactive guidance tool library for web novices, powerful and highly customizable

UML类图

Driver.js - 开源无依赖的 web 新手交互引导工具库,功能强大、高度可定制

IO file stream repeat read

使用SoapUI工具生成发送短信接口代码

Collected data, must see
随机推荐
Practical cases, in-depth analysis
FM4057S单节锂电池线性充电芯片的学习
【严选】,真题解析
How to insert PDF into ppt as vector graph
Minimalist random music player
ShaderGraph——水晶
使用SoapUI工具生成发送短信接口代码
(11) Const decorated member function
Shadergraph - 302 swimming Dragon
Using Joern to process a large number of files and generate PDG is a slow solution
Uni app parses the bank card (Alipay) and returns the form, evoking the Alipay interface
js禁止复制页面内容
IO file stream repeat read
C語言最佳實踐之庫文件介紹(下)
(8) Initialization list
Shadergraph - Crystal
【已解决】vagrant up下载box速度太慢的解决方法
MAX3051的can芯片的学习
掌握高性能计算前,我们先了解一下它的历史
dom4j解析xml