[英]Write a while loop that prints all positive numbers that are divisible by 10 and less than a given number n
I have this homework problem and I cannot seem to get it at all.我有这个家庭作业问题,但我似乎根本无法解决。 the suggested outcome if n were to be 100 would be 10 20 30 40 50 60 70 80 90
如果n为100 ,则建议的结果为10 20 30 40 50 60 70 80 90
I know my question is probably really stupid but I cannot seem to understand this for the life of me.我知道我的问题可能真的很愚蠢,但我似乎无法理解这一点。
Scanner in = new Scanner(System.in);
System.out.print("n: ");
int n = in.nextInt();
while (n % 10 < 1)
{
System.out.print(n + " ");
n = n - 1;
}
System.out.println();
There are many solutions, you can do it with help of an extra variable.有很多解决方案,您可以借助一个额外的变量来完成。
Scanner in = new Scanner(System.in);
System.out.print("n: ");
int n = in.nextInt();
int iter = 10;
while(iter < n)
{
System.out.print(iter + " ");
iter += 10;
}
I guess you were trying to make the program without using an extra variable, but you have to take an extra variable if you want all the numbers to be displayed in increasing order.我猜你试图在不使用额外变量的情况下编写程序,但如果你希望所有数字以递增顺序显示,则必须使用额外变量。 You can try this code snippet out.
您可以试试这个代码片段。 It will work.
它会起作用。
Scanner in = new Scanner(System.in);
System.out.print("n: ");
int n = in.nextInt();
int a = 10;
while(a <= n){
System.out.print(a+" ");
a += 10;
}
Not in Java, but here is my solution in C++ where I just decrement n by 10 because it needs to round down.不在 Java 中,但这是我在 C++ 中的解决方案,我只是将 n 减 10,因为它需要向下舍入。
#include <iostream>
using namespace std;
int main()
{
cout << "n: " << endl;
int n;
cin >> n;
int count = 0;
while (count < (n-10))
{
count += 10;
cout << count " ";
}
cout << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.