If-else loop to find solution - c++

My code is:
#include<stdio.h>
void main(void)
{
float timeLeavingTP;
int transitNumber;
float transitTime;
printf("Please enter the time leaving TP.\n");
scanf_s("%f",&timeLeavingTP);
printf("Please enter bus number.\n");
scanf_s("%d",&transitNumber);
if(timeLeavingTP==1.00)
{
if(transitNumber==27)
{
transitTime=1.56;
}
else if(transitNumber==8);
{
transitTime=1.39;
}
}
if(timeLeavingTP==6.30)
{
if(transitNumber==27)
{
transitTime=7.32;
}
else if(transitNumber==8)
{
transitTime=7.29;
}
printf("The time reached home is %f\n",transitTime);
}
}
After debugging i got
Please enter the time leaving TP
1.00
Please enter bus number
27
Please enter to continue...
My question is How do i adjust the program to make it look like the one below instead. What kind of error did i commit?
Please enter the time leaving TP
1.00
Please enter bus number
27
The time reached home is 1.56
Thanks for the help in advance!
Hi guys after including == i still got the same for my debugging? Is there something else that i did wrong?

Part 1: = vs ==
Note that:
if(timeLeavingTP=1.00)
Does not do what you expect. It assigns timeLeavingTP with 1.00.
You probably want:
if(timeLeavingTP==1.00)
Additionally, note that this error occurs 6 times in your program.
Part 2: comparing floating point numbers
Your code might work in this case, but I'm not 100% sure if it will or not. It's often difficult to directly compare 2 floating point numbers, because of the inaccuracy of storing them (for example, 0.1 is usually not representable in floating point).
Most people solve this problem in one of a few ways:
Test a range around the number.
Convert to some fixes width format. Perhaps you could store the number as an integer, knowing that it's representation is actually 0.01 * the stored number.
In this case, you could actually just store the information as strings, and compare those.
Part 3: conditionals
To write a proper conditional, it should look like:
if (condition) {
...
} else if (condition) {
...
} else if (condition) {
...
} else {
...
}
You can certainly nest conditionals as well:
if (condition) {
if (condition) {
...
} else {
...
}
} else if (condition) {
...
}
Your code, for example, messes this up when you do:
}
else(transitNumber=8);
{
transitTime=1.39;
}
Note that the else statement does not accept a conditional after it.
Part 4: excessive semicolons
Additionally, note that after the else and if statements there are no semicolons. The semicolons only appear within the braces. So this statement:
if(timeLeavingTP=6.30);
While semantically valid, does not do what you expect. You actually want to remove that semicolon.

if(timeLeavingTP == 1.00)
{
if(transitNumber == 27)
{
transitTime=1.56;
}
else if(transitNumber == 8)
{
transitTime=1.39;
}
}
else if(timeLeavingTP == 6.30)
{
if(transitNumber == 27)
{
transitTime == 7.32;
}
if(transitNumber ==8)
{
transitTime=7.29;
}
}
printf("The time reached home is %f\n",transitTime);
}

if(transitNumber=27)
{
transitTime=1.56;
}
else(transitNumber=8);
{
transitTime=1.39; //this line is executed all the time
}
This code is completly invalid!
First, you do not compare anything... transitNumber = 27 is an assignment.
Second else(transitNumber=8); again this is an assignment and it should be else if(...). Also ; at the and means that transitTime = 1.39(inside bracket) will always happen, even if transitNumber != 8

Change
if(timeLeavingTP=1.00)
to
if(timeLeavingTP==1.00)
so that you can compare timeLeavingTP correctly.

Related

Return 0 in if statement, does it means true/false or the program runs successfully?

First, if return 0 statements are removed, my program cannot run exactly. So I don't understand what does this means.
Secondly, one more problem is that it doesn't print the string "Accept 1-4 key only." at the end. If I press others key(not 1-4), the program stop and exit.
When I change if- else if statement to switch. It can run.
I am not able to figure what is going wrong in the program?
char key;
key = getchar();
fflush(stdin);//fpurge(stdin);
//1. play game
if (key == '1') {
if (Money >= 0.25) {
Money = Money - 0.25 + PlayGame();
}else {
printf("\nYou dont have enough money to play\n");
SaveGame (Money, "d:/SaveGame.txt");
return 0;
}
//2. Save game
}else if (key == '2') {
SaveGame (Money, "d:/SaveGame.txt");
//3. Cash out
}else if (key == '3') {
printf("Thank you for playing, you end with %.2f", Money);
remove("d:/SaveGame.txt");
return 0;
//4. Quit
}else if (key = '4') {
remove("d:/SaveGame.txt");
return 0;
//5. Wrong key
}else {
printf("Accept 1-4 key only.");
}
}while(1);
return 0;
}
return 0 is a programming convention that is used during program exit to indicate that the program have executed without errors. On the other hand, a > 0 return code indicates an error is encountered.
On your question, if return 0 is removed, program cannot run. It just means that the function that you are using is expecting an integer to be returned like below.
int main() {
....
}
If you are willing, you can also consider using switch/case statements instead of if/else. Note also that there is a logic error on your last else if. Should be key == '4'.
Assuming you have used int main() to run the code. int main() is a function in c/c++ with return type int, hence, you are supposed to use a return statement to run the code without errors.
Now, return 0 is a programming convention which indicates that program has executed without errors.
else if (key = '4') indicates assignment operator, not comparison operator which is ==.
If this code is inside the main function, there are three portable return values: 0, EXIT_SUCCESS, and EXIT_FAILURE. The latter two are constants that are defined in the header <cstdlib>. Returning 0 is equivalent to returning EXIT_SUCCESS. The values of those two constants are determined by the target system, that is, they will be values that the OS treats as success and failure, respectively.
In short: return 0; tells the system that the program succeeded. So does return EXIT_SUCCESS;. return EXIT_FAILURE; tells the system that the program failed.
There's one quirk here, though: in C++ (but not in C) you can leave out the final return statement from main:
int main() {
}
when execution reaches the end of main, it acts as if there was a return 0; just before the closing }. Personally, I've never liked that; I always write return 0; at the end of main. Your mileage may vary.

How to generate a boolean condition during runtime in C++?

I want to be able to generate a boolean condition during the runtime based on the states of some variables. My task looks simple at first. I have a large if () else if () statement what needs to determine if the number is in a certain range. It then does something depending on whether that number is inside that range.
Here's pseudocode to demonstrate what I want:
void fun(int num, int offset = 0) {
if (0...60) {
// do something
} else if (60...180) {
// do something else
} else if (180...240) {
} else if (240...360) {
}
}
The first if statement should work like this:
if (0 >= num && num <= 20) {
// do something
}
The caveat here is that in addition to int num, there is another parameter passed in, which I call the offset. The structure of the code here, including the do something inside the { } is the same. The only things that need to change are are ranges, based on the value of the offset. By the way, this is not a default parameter here, it is just pseudocode demonstrating what the value of int offset was passed in.
void fun(int num, int offset = 120) {
if (120...180) {
// do something
} else if (180...300) {
// do something else
} else if (300...360) {
} else if (360...120) {
}
}
That last else if () statement has been giving me some trouble.
} else if (360...120) {
}
What I'm actually trying to write here is:
} else if (num >= 360 || num <= 120) {
}
The reason for this is that my int num may have a value > 360. However, in that case for the purpose of my application it has to "wrap around" and be treated as a value 0...120.
This is for a mathematical application here. Whenever you have int num > 360, you go around the full circle and you end back at 0 where you started. So that is the effect which I want to achieve.
I don't want to write extra functions. I want my code to be generic because many different values for int num and int offset may be passed into my function. I want to generate the necessary conditions during the runtime based on the value of int offset.
The main problem here is that in the first situations, when int offset = 0 my condition is
} else if (240 >= num && num <= 360) {
}
However, for a different offset we wrap around and so I have to change the format of the entire condition! For example, when int offset = 120, as shown above:
} else if (num >= 360 || num <= 120) {
}
The problem is that in the first situation I had the && in the last else if (), but now I have the || to convey the same meaning. What I'm looking for is a way to be able to manipulate the operators inside the conditional statements as mere chars in a string, then "paste" the completed condition into the if () statements during the runtime!
What's even worse is that this "wrapping around" can occur inside any one of the if () statements, not just the last one. It is based on the value of the offset.
I can't use preprocessor tricks, because I want this to work during the runtime. Maybe it is possible to use function pointers or something for this, but I don't know how to do that. Please note that the ... above is not real C++ code, it is pseudocode! I'm aware that there is a "range-based" switch statement in C++, but I can't use that because of the "wrapping around" property mentioned above.

Program to find greatest common divisor

Here's a c++ program i tried to write for the above question.Our teacher told us to use a for loop.
void main()
int A[30],B[30],m,n,i,j,x,z;
cout<< "enter two numbers";
cin>>m>>n;
for(i=1,j=0;i<=m,j<30;i++,j++)
{
if(m%i==0)
{ A[j]=i;
z=j;
}
}
for(i=1,j=0;i<=n,j<30;i++,j++)
{
if(n%i==0)
{ B[j]=i;
x=j;
}
}
for(i=z;i>=0;--i)
{
for(j=x;j>=0;--j)
{
if(A[i]==B[j])
{ cout<<"gcd="<<A[i];
}
}
}
}
The output displays " Enter two numbers:" and when i entered 15 and 3, the result i got was a blinking cursor. Working through the program, I realised that the divisors for each number when stored in the arrays of A and B were not stored continuously or had gaps in between. If there isn't anything in the memory for say A[11], what happens when you check it against another variable with a number? Can somebody please modify this to make it work and tell me what's wrong? I am new to programming, so excuse my program if it is clumsy.
Andreas has pointed out that there are other ways to achieve the goal of finding the gcd, but the point of the exercise is to get a better handle on some basic programming constructs. So lets go with your approach.
Your idea is to compute the two lists of divisors and then compare them. As you say, having a list with gaps in makes this harder.
So adapt your loop, only increment the storage index when you've stored something
for(i=1,j=0;i<=m && j<30;i++) // need the && here; a comma means something different
{
if(m%i==0)
{ A[j++]=i;
z=j;
}
}
Second, you have a typo you're not storing in B, so fix that
for(i=1,j=0;i<=n && j<30;i++)
{
if(n%i==0)
{ B[j++]=i; //B here not A
x=j;
}
}
That should help.
Try this:
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
As taken from here: https://codereview.stackexchange.com/questions/66711/greatest-common-divisor

OpenCL Out of Resources - Crash at code line which is not reached at that moment

i'm doing some OpenCL programming and at one location in my code I get strange error.
a and a_end are pointers to local memory
if (a+POS<=a_end) {
max = ....
} else {
max = *(a_end-1);
}
In my case "else" isn't reached in the current loop. However, the application crashes with -5 CL_OUT_OF_RESOURCES if the line is part of the code.
If I comment the line the program works well. This is very strange.
Do you have any suggestions?
Regards,
Chris
Edit: Some more code
Values of a, a_end and POS1 before it crashes:
a: 3298304
a_end: 3311264
POS1: 34
border=b-b_end; //TODO: Check if all dummy elements are removed in this case
if(POS1<border && a+POS1<a_end) {
s_data[POS1+s_maxes[2]-border+1]=a[POS1];
s_ids[POS1+s_maxes[2]-border+1] = a_pos+POS1;
}
if(POS1+1==border) {
debug[0] = a+POS1;
debug[1] = a_end;
s_maxes[1]=*(b_end-1);
if(a+POS1<=a_end) {
s_maxes[0]=s_data[s_maxes[2]];
} else {
s_maxes[0]=*(a_end-1); //Here is the line where it crashes
}
}
if(POS2<border && a+POS2<a_end) {
s_data[POS2+s_maxes[2]-border+1]=a[POS2];
a_pos+POS2;
}
if(POS2+1==border) {
s_maxes[1]=*(b_end-1);
if(a+POS2<=a_end) {
s_maxes[0]=s_data[s_maxes[2]];
} else {
s_maxes[0]=*(a_end-1);
}
}
a+=border;a_pos+=border;
There is a good chance that the following scenario happens: before your if the value of a_end is corrupted, highly possibly it gets initialized to 0 (without further knowledge of the code this is my best shot, but it also might be a value which is smaller than a + POS) and then obviously the else branch gets executed which tries to de-reference the value found at address 0 - 1 which is a pretty big number and then the application crashes. Obviously if you remove the else branch this code is not executed.
Hint: Put some printouts for the value of a_end.

C++ Prime factor program 2 problems

Okay so I"m writing a program (in C++) that is supposed to take a number, go through it, find out if it's factors are prime, if so add that to a sum, and then output the sum of all of the imputed number's prime factors.
My program successfully seems to do this however it has 2 problems,
1) The number I am supposed to test to see the sum of the prime factors of this number (600851475143) but it's too big for an int. I'm not sure what other variable type to use, or which variable's types to change. I would really like a clear explanation on this if at all possible.
2) For some reason, when the program checks to see if 1 is a factor of the number, and then checks to see if 1 is prime, it says 1 is prime, even though the first step of the function for checking to see if it's prime is that if it's 1 then it isn't prime. I found a fix for this, by telling it to subtract 1 from the very last value for the sum of all prime factors. However, this is a fix, not really finding the problem. If someone could point out at least where the problem is I would appreciate it!
Here's the code, if you have questions, please ask!
#include <iostream>
using namespace std;
bool prime (int recievedvalue) { //starts a function that returns a boolean with parameters being a factor from a number
int j =1;
int remainderprime = 0;
bool ended = false;
while (ended == false){ //runs loop while primality is undetermined
if (recievedvalue == 1){ //if the recieved value is a 1 it isn't prime
//not prime
break; // breaks loop
return false;
}
remainderprime=recievedvalue%j; //gives a remainder for testing
if ((remainderprime==0 && j>2) && (j!=recievedvalue || j == 4)){ //shows under which conditions it isn't prime
ended=true;
//not prime
return false;
}
else if (j==1){
j++;
}
else if ( recievedvalue==2 || j==recievedvalue ){ // shows what conditions it is prime
ended = true;
//prime
return true;
}
else {
j++;
}
}
}
int multiple(int tbfactor){ //factors and then checks to see if factors are prime, then adds all prime factors together
//parameter is number to be factored
int sum = 0;
bool primetest = false;
int remainderfact;
int i=1;
while (i<=tbfactor){ //checks if a i is a factor of tbfactor
remainderfact=tbfactor%i;
if (remainderfact==0){ //if it is a factor it checks if it is a prime
primetest = prime(i);
}
if (primetest ==true){ //if it is prime it add that to the sum
sum += i;
primetest=false;
}
i++;
}
sum --; // for some reason it always ads 1 as a prime number so this is my fix for it
return sum;
}
int main()
{
int input;
int output;
cout << "Enter number to find the sum of all it's prime factors: ";
cin >> input;
output = multiple(input);
cout << output;
return 0;
}
I'm really new to this, like a few days or so, so I'm very unfamiliar with stuff right now so please explain easily for me! I look forward to your help! Thanks!
For 1), you need to use a larger datatype. A 64-bit integer should be enough here, so change your ints to whatever the 64-bit integer type is called on your platform (probably long, or maybe long long).
For 2), the problem appears to be that you have a break before your return false. The break causes the code to stop the while loop immediately and continues execution immediately after the loop. It doesn't appear that the return value is ever assigned in that case (which your compiler should be warning you about), so the actual value returned is effectively arbitrary.
While others have pointed out a problem with your data types, there's a few problems with the structure of the first function that immediately caught my eye. (BTW, your indentation is enraging.) Look at this stripped-down version:
bool prime (int recievedvalue) {
// ...
bool ended = false;
while (ended == false){
if (...){
break; // jumps _behind_ the loop
return false;
}
// ...
if (...) {
ended=true;
return false; // leaves function returning true
}
else if (...) {
// ...
}
else if (...) {
ended = true;
return true; // leaves function returning false
}
else {
// ...
}
}
// behind the loop
// leaves function returning random value
}
For one, every time you set the loop control variable ended, you leave the loop anyway using some other means, so this variable isn't needed. A while(true) or for(;;) would suffice.
Also, that break jumps behind the loop's body, but there isn't a statement there, so the code leaves the function without explicitly returning anything! That's invoking so-called Undefined Behavior. (According to the C++ standard, your program is, from this point on, free to do whatever it pleases, including returning random values (most implementations will do that), formatting your HD, invoking nasty Nasal Demons on you, or returning exactly what you expected, but only on Sundays.)
Finally, that break occurs right before a return false; which is therefor never reached. Actually your compiler should warn about that. If it doesn't, you're likely not compiling at the highest warning level. (You should turn this on. Always try to cleanly compile your code at the highest warning level.) If it does, learn to pay attention to compiler warnings. They are a very important tool for diagnosing problems during compilation. (Remember: Errors diagnosed during compilation need no testing and never make it to the customer.)
Use either a 64 bits number on a 64 bits system, or use a library that does arbitrary precision arithmetic
Remove the break before the return false. Because of the break, execution is resumed outside the loop and return false is never executed.
To store values larger than 4 bytes (the capacity of an int) you have a variety of options. Refer to this page for those options. As to why you're program is returning true for the check on whether or not 1 is prime, check out this section of code:
if (recievedvalue == 1){ //if the recieved value is a 1 it isn't prime
//not prime
break; // breaks loop
return false;
}
The break statement will exit and return false will never be reached. To solve the problem, remove the break statement.