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
Go through the program line by line. With cin>>x, you read a number into x. Line 6 is a while (1), 1 is true, so you go into the loop. The next cin>>x reads a number into x, overwriting the previous contents.
(x>0 && (x%5==0)) ? int(x/5) : -1;
^^
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.
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/.
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 to int?
Related
This question already has an answer here:
if statement works with any input [closed]
(1 answer)
Closed 2 years ago.
I have to write a program that calculates the formula inputted from the user. For example:"input: 1+2", "output: 3", but I keep getting a number after the answer like this:"input: 1+2", "output: 3-12". How do I get rid of that -12 behind the 3? And why is it giving me that number? Here is the code:
#include <iostream>
using namespace std;
int main(){
int n,m;
char x;
cin>>n>>x>>m;
if(x='+'){
cout<<n+m;
}
if(x='-'){
cout<<n-m;
}
if(x='*'){
cout<<n*m;
}
}
Please help, Thanks.
The expression in the if statement:
if(x='+')
doesn't compare x to +, but instead assigns + to x. That means every single one of your if statements evaluates to true, and you get 3 numbers as output, i.e. 3, -1, and 2.
The correct way to do a comparison is:
if(x == '+')
If you turn on all your warnings, the compiler will tell you that you did something wrong.
First you made the '=' operation this will make the value assign to the variable so you must made it like this;
if (x == '*')
It will solve the problem.
Second in the '-' operation you kind of will have a problem when the first number is less than second number it will get you a negative number to solve it you will make a simple if statement to prevent this from happening;
if (x=='-'){
if(n>m)
cout << n-m << endl;
else
cout << m-n << endl;
}
so you tell the computer that if the first number bigger than the second number so subtract the first number,
else if first number is less than the second number then, subtract the second number from the first number, by this you will prevent the user form getting negative number if you want.
This is a model solution code of the following problem;
"The input consists of T test cases. The first line of the input is given a T.
Each test case consists of three rows of integers separated by a single space, each consisting of three random points of x and y coordinates. The coordinates of the top left pixel in the browser viewport are (1, 1) and the coordinates of the bottom right pixel are (1000, 1000). All coordinates are located within the viewport and the positions of each point are different."
And here is the sample of the input.
2
5 5
5 7
7 5
30 20
10 10
10 20
7 7
30 10
The last two lines are the answers of the problem.
And here is my three questions.
1) What happened when we use cin statement in initialization?? It receives how many actions it will perform from the user in the initialization of for loop. I understand that this cin statement works properly. I cannot understand how this code knows how many times this for loop has to be repeated. This is because there is no action on T after initialization with a value of T from the user. There is no actrion in 'increment/decrement' also.
2) After googling, I understand when there is cin in condition, the loop ends when there is no more inputs or the inputs' type does not match the variables' type. But in this code, the for loop ends when the repeated time (T) is over. How could this happen???
3) Finally, the outcomes should be presented after all inputs are finished not by one-by-one. Then how could this for loop memorize the outcome of each set(3 inputs)??
I'm not English speaker T.T Thank you for reading my question.
#include<iostream>
int main()
{
int T,a,b,c,A,B,C;
for(std::cin>>T; std::cin>>a>>A>>b>>B>>c>>C; printf("%d %d\n",a^b^c,A^B^C));
}
What happened when we use cin statement in initialization??
That part of for() loop can contain any simple statement, not
just initialization statement. This statement is done only once. For
loop
for ( init condition ; iteration )
statement
is actually equivalent of this code:
{
init
while ( condition )
{
statement
iteration;
}
}
But in this code, the for loop ends when the repeated time (T) is
over. How could this happen???
The operator >> overloaded for streams return stream it acted on. Class
ios_base which is common parent of all streams, contains this
operator
std::ios_base::operator bool()
This operator is an equivalent of good() method. When >> fails to read and parse values from input stream, good() returns false,
loop breaks. T is not used in the provided code.
Then how could this for loop memorize the outcome of each set(3
inputs)??
It doesn't. It prints result after reading each set.
PS. People who read\proof-check code after programmer, would tend to have murderous intent toward those who write for() loops like that.
If we use a cin statement as our initialization, we execute this once. It will receive the input and place the value in the variable T. You are completely right; there is no action on T after initialization such as incrementing or decrementing its value.
This is not true. The code does not end when the it repeated T times. As long as (valid) input is given, this for-loop will continue. This is because the condition part of your for-loop consist of a cin statement. That is, as long as your cin statement succeeds, the for-loop will continue.
It cannot. Each time the loop runs, you overwrite the variables a, A, b, B, c and C. Hence, the old values are lost.
I would like some confirmation (or refutation) about something.
I was just busy with a simple exercise placing statements inside loop conditionals. Basically I created an array of 5 elements and then have the user input 5 values that will be stored in the array. Pretty basic stuff. But then I started wondering: What if I replaced the a[i++] in my code with simply a[i]? So I did, and the resultant output was that I (i.e. the user) just kept inputting values seemingly infinitely, i.e. not stopping at only 5 inputs.
Now then I made the assumption that what might be happening is that now the program simply replaces every new input value with the previous one and storing it in element 0 of the array, over and over, hence it not stopping at 5.
Is this assumption of mine is correct? If not, then please shed some light on what exactly is happening here. This might be a very nonsensical thing to be concerned about, but I'd really like to know either way.
//array test
#include <iostream>
int main()
{
int a[5] = { 0 };
int i = 0;
while(std::cin >> a[i++] && i < 5);
return 0;
}
So, you are basicly asking what's the difference between i and i++? It's rather basic C/C++ (note the ++ here!). I suggest you google for "C++ postincrement operator" :)
If you remove the i++ and replace it with only i, you are replacing a[0] indefinitely.
a[i++] evaluaves to a[i], and AFTER that increases i by one. So when i reaches 5, the second part of your condition (i<5) is not true and exits from the while loop.
Yes, you're correct.
Just test it, remove the ++ and run.
If you want "having a loop with no code inside", do not use std::cin >> a[i++] expression as condition (I think it will always true). Better use comma operation, e.g.:
while(std::cin >> a[i++], i < 5);
Moreover, in the condition expression like (std::cin >> a[i++]) && (i < 5) left part (i.e. (std::cin >> a[i++])) can be skipped because optimization done by compiler (so i++ will not be executed).
I wish to take inputs from console where the number of inputs are not known. All i know is that they are less then or equal to 10.
I wrote this code but it evaluates the last value twice.
int x;
do{
cin>>x;
cout<<check(x)<<"\n";
}while(std::cin);
The inputs are in this form:
12
2
45
As #LightnessRacesinOrbit commented, it's while(!eof) bug again. You should check the stream state after reading from it, not before.
You can use cin>>x in the while-condition and apply a special value (i.e. anything not a number) as the end flag like this:
while (cin >> x)
{
// got a value
}
You may use istream::geline.
char input[1024]
std::cin.getline (input,1024);
After you read the line, you have to split it by white-spaces as delimiter. Just ignore 11th split onwards. And you may apply atoi or similar functions on the splits (some_split.c_str()) to get the numeric values
I am trying to give a shot at Project Euler problem 3 until codeblocks or whatever caused it pissed me off. This is my code, What is wrong with it? I guess more of a bug?
#include <iostream>
using namespace std;
int main()
{
int x=0;
for(int y=0;y<=10;y++)
{
if(13195%x==0)
{
cout<<"I don't know why the program crashes!";
}
}
}
You can't use a 0 as the second operand while doing / or %. What you're essentially saying is "Hey divide by 0 and give me the remainder." Please see the following:
Can't Mod Zero?
Modulus operator divides it by zero and next finds the remainder, thus you will get divide by zero error
x must not be equal to 0 otherwise division by zero.
Just think how many zeroes in 13195?
x = 0. Dividing a number with zero will crash your code. Make sure x is not 0 before 13195 % x.
The operation A modulo B is defined as: the remainder of the division of A by B.
In your code, you have B=0 which means you are trying to divide by zero.