gpt4 book ai didi

java - 试图找到负指数的答案,只有正指数和 0 有效

转载 作者:行者123 更新时间:2023-11-30 08:17:18 25 4
gpt4 key购买 nike

我在寻找答案时无法使用数学课。计算答案时我必须使用 for 循环。

package Powers;

import TerminalIO.KeyboardReader;

public class powers {
public static void main(String [] args)
{
KeyboardReader reader= new KeyboardReader();
//Variables
int base; //The base number for the calculations
int minE; //The minimum exponent that will be used
int maxE; //The maximum exponent that will be used
int answer; //Weather the user wishes to repeat or not
double result = 1; //The result of the base to the power of the exponent

//Inputs
do { /* Start of repeat */ base = reader.readInt ("Please enter the base. ");
minE = reader.readInt ("Please enter the minimum exponent. ");
maxE = reader.readInt ("Please enter the maximum exponent. ");
//Error Checking
while (minE > maxE) {
System.out.println("There seems to be an error, your minimum exponent is greater then your maximum exponent. Please re-enter your values");
minE = reader.readInt("Enter your minimum exponent. ");
maxE = reader.readInt("Enter your maximum exponent. ");
}
//End of Error Checking

//Calculations
//Output
System.out.println(" Base Exponent Result");
System.out.println();
int expo; //The exponent by which the base will be powered to
for (expo = minE; expo <= maxE; expo++) {

//For exponent being 0
result = 1;
//For exponent being <0
if (expo <0) {
for (int i= minE;i != 0;i = i + 1) {
result = result/base;
}
}

if (expo == 0) {
result = 1 ;
}

//For exponent being 1
if (expo == 1) {
result = base;
}
//For exponent being >1
if (expo > 1) {
for (int i=1;i<=expo;i++) {
result = result*base;
}
}



System.out.println( " " + base + " " + expo + " " + result);
}
System.out.println();
answer = reader.readInt ("Do you wish to repeat? Enter 1 if yes.");
} while (answer == 1); //End of repeat

}

出现的示例答案是

Please enter the base. 2
Please enter the minimum exponent. -2
Please enter the maximum exponent. 2
Base Exponent Result

2 -2 0.25
2 -1 0.25
2 0 1.0
2 1 2.0
2 2 4.0

如您所见,只有 0 和积极的工作,而不是消极的。

最佳答案

你对 i 的初始化错误。将 i= minE 改为 i= expo

for (int i = expo; i != 0; i = i + 1) {
result = result/base;
}

关于java - 试图找到负指数的答案,只有正指数和 0 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27935924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com