如何获取程序的指定输出? [英] How do I get the specified output for my program?

查看:61
本文介绍了如何获取程序的指定输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

读取输入数字(比如n)并计算表达式n + nn + nnn的值的Java程序?

我用5号试过它,预期输出应该是5 + 55 + 555 = 615。但输出是7320.请检查我的代码并建议任何更正。



谢谢。



我尝试过:



import java.util.Scanner;

public class Formula {



public static void main(String [] args){

// TODO自动生成的方法存根

扫描仪输入=新扫描仪(System.in);

System.out.print(输入数字:);

int n = in.nextInt ();

int sum = 0;

for(int i = 0; i< = 3; i ++){

sum = sum + n;

n = n * 11;

}

System.out.print(sum);

}



}

A Java Program that reads an input digit (say n) and computes the value of the expression n+nn+nnn ?
I have tried it with number 5 and the expected output should be 5+55+555=615. But the output was 7320. Please check my code and suggest any corrections.

Thanks.

What I have tried:

import java.util.Scanner;
public class Formula {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("Input number : ");
int n = in.nextInt();
int sum=0;
for(int i=0 ; i<=3 ; i++) {
sum = sum+n;
n=n*11;
}
System.out.print(sum);
}

}

推荐答案

尝试使用调试器查看程序中发生了什么。你会看到发生了以下情况:



迭代1:n = 5

迭代2:n = 5 * 11 = 55

迭代3:n = 55 * 11 = 605

迭代4:n = 605 * 11 = 6655

sum = 5 + 55 + 605 + 6655 = 7320
Try use the debugger to see what's going on in your program. You'll see what's happening is the following:

Iteration 1: n = 5
Iteration 2: n = 5*11 = 55
Iteration 3: n = 55*11 = 605
Iteration 4: n = 605*11 = 6655
sum = 5 + 55 + 605 + 6655 = 7320


这篇关于如何获取程序的指定输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆