如何不打印此计算中的最后一个加号

好吧,所以也许这似乎是一个带有简单解决方案的愚蠢问题,但现在我找不到解决方案,也没有找到任何答案。


这是我的问题的相关代码:


int sum = 0;

    for ( int i = minLim; i <= maxLim; i++) {

        sum += i;

        System.out.print(i + " + ");

    }

    System.out.print("= "+sum+" ");

这打印:2 + 3 + 4 + 5 + 6 + = 20


minLim 和 maxLim 的值是从用户输入中读取的。


但我想让它不会打印最后一个“+”。怎么做?还有一个额外的问题:对于每打印出 10 个数字,我想要一个新行,以便第 11 个数字打印在另一行上,依此类推。谢谢!


守着星空守着你
浏览 147回答 3
3回答

慕妹3146593

int sum = 0;for (int i = minLim ; i <= maxLim ; i++) {&nbsp; &nbsp; sum += i;&nbsp; &nbsp; if (i == maxLim)&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(i);&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(i + " + ");&nbsp; &nbsp; }&nbsp; &nbsp; System.out.print("= "+sum+" ");}

蝴蝶不菲

您可以添加一个if来检查您何时到达最后一个号码。像这样的事情:for ( int i = minLim; i <= maxLim; i++) {&nbsp; &nbsp; &nbsp; &nbsp; sum += i;&nbsp; &nbsp; &nbsp; &nbsp; if (i + 1 <= maxLim)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(i + " + ");&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(i + " ");&nbsp; &nbsp; }

哔哔one

您已经看到了一些解决方案,它们采用了在最后一个加数之后不打印a的方法。 +但是你可以很容易地采取相反的观点:在每个加数之前打印一个+ ,除了第一个:int sum = 0;for ( int i = minLim; i <= maxLim; i++) {&nbsp; &nbsp; sum += i;&nbsp; &nbsp; if (i > minLim)&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" + ");&nbsp; &nbsp; System.out.print(i);}System.out.print("= "+sum+" ");或者,如果您不喜欢在 loop内测试循环的开始条件或结束条件的想法,您可以使用boolean变量作为一次性标志而不是测试i:int sum = 0;boolean firstTime = true;for ( int i = minLim; i <= maxLim; i++) {&nbsp; &nbsp; sum += i;&nbsp; &nbsp; if (!firstTime)&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" + ");&nbsp; &nbsp; firstTime = false;&nbsp; &nbsp; System.out.print(i);}System.out.print("= "+sum+" ");都是不错的选择,随便挑...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java