运行 while 的第一个实例
作业:
编写一个无限循环的程序。在循环的每次迭代中,读入用户输入的整数
N
(声明为 int),如果 N 为非负且可被 5 整除,则显示 N/5,否则显示 -1否则。使用三元运算符 (?:) 来完成此操作。 (提示:模运算符可能有用。)
我的解决方案:
#include<iostream>
using namespace std;
int main(){
int x;
cin>>x;
while(1) {
cin>>x;
int result;
cout<<" "<<endl;
result = (x>0 & (x%5==0)) ? int(x/5) : -1;
cout<<result;
}
}
我能够做这个问题 但程序的第一次运行没有给出输出
The assignment:
Write a program that loops indefinitely. In each iteration of the loop, read in an integer
N
(declared as an int) that is entered by a user, display N/5 if N is non-negative and divisible by 5, or -1 otherwise. Use the ternary operator (?:) to accomplish this. (Hint: the modulus operator may be useful.)
My solution:
#include<iostream>
using namespace std;
int main(){
int x;
cin>>x;
while(1) {
cin>>x;
int result;
cout<<" "<<endl;
result = (x>0 & (x%5==0)) ? int(x/5) : -1;
cout<<result;
}
}
I am able to do the question
but the first run of the program does not gives output
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
逐行浏览程序。使用
cin>>x
,您可以将一个数字读入x。第 6 行是一个while (1)
,1 为 true,因此进入循环。接下来的cin>>x
读取一个数字到x中,覆盖之前的内容。Go through the program line by line. With
cin>>x
, you read a number into x. Line 6 is awhile (1)
, 1 is true, so you go into the loop. The nextcin>>x
reads a number into x, overwriting the previous contents.我认为您打算使用逻辑
&&
运算符,而不是按位&
运算符。此外,您正在读取
x
两次并覆盖第一个读取的值。I think you intend to use Logical
&&
operator and not the bitwise&
operator.Additionally, You are reading into
x
twice and overwriting the first read value.好的。首先第一件事。你应该知道C++逻辑与运算符是“&&”而不是“&” (你用过的那个)。看看这里: http://www.cplusplus.com/doc/tutorial/operators/< /a>.
Okay. First thing first. You should know C++ logical AND operator is "&&" and not "&" (the one you used). Have a look here: http://www.cplusplus.com/doc/tutorial/operators/.
提示 1:您真的需要 while 循环上方的单例
cin
吗?提示2:是否要打印结果上方带有换行符的空行?
提示3:是否需要打印不带换行符的结果?
提示 4:您是否打算使用按位
&
而不是逻辑&&
?可选
提示 1:是否需要将
5
的除法转换为int
?Hint 1: Do you really need the singleton
cin
just above the while Loop?Hint 2: Do you want to print the blank line with newline above the result?
Hint 3: Do you need to print the result without a newline?
Hint 4: Did you intend to use a bitwise
&
instead of logical&&
.?Optional
Hint 1: Do you need to case the division by
5
toint
?