Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

Java Infinite Loop Problem - With Unknown Variable

I'm working through a course from Coursera. I am trying to find a solution for their infinite while loop question with an unknown variable.

The Problem Is:

int i = 1;
while (<<?>>) {
    i = i*n;
}

What should be written in place of <<?>> so that the loop ends when i is at least 34? You may assume n is an int variable that has been declared and given a value prior to this code (the value of n does not affect the answer to this question).

I tried for the condition, i % 34 = 0, i<=34, etc. but I couldn't find the right answer. And they aren't giving the solution for this problem.

How can I solve this problem without knowing n's value?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

i<=34 is almost right, but the requirement is to end the loop when i is at least 34. I.e., if i is 34, the loop should not continue, which means you should use the < operator, not the <= operator:

while (i < 34) {
    i = i*n;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...