Open Side Menu Go to the Top

02-08-2016 , 08:28 AM
Quote:
Originally Posted by ChrisV
In duck-typed or other dynamic languages, using errors as a way to control execution flow is totally acceptable. The Python community even has an acronym EAFP - "easier to ask for forgiveness than permission", meaning the "pythonic" way to code is often to attempt to do what you want to do and handle errors if it doesn't work.
no.
Programming homework and newbie help thread Quote
Programming homework and newbie help thread
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Programming homework and newbie help thread
02-08-2016 , 09:39 AM
alright, correct me then. dont be the ikestoys of the programming subforum.
Programming homework and newbie help thread Quote
02-08-2016 , 10:44 AM
Quote:
Originally Posted by ChrisV
Also helpful is using a non prehistoric language that accomplishes these things natively.
Not prehistoric at all. Try enhancing and maybe even rewriting a Linux kernel (Any OS, even a JVM) in C#. On the other hand, try writing an enterprise type app interfacing to DBs, providing a UI, etc. in C interfacing your code to the latest version of .NET instead of C#. Clearly there are problem domains appropriate for each language. The right language for the right problem domain.

Last edited by adios; 02-08-2016 at 10:56 AM.
Programming homework and newbie help thread Quote
02-08-2016 , 11:03 AM
Quote:
Originally Posted by fruit snacks
I thought because arrays in c are essentially just pointer arithmetic, it would just read in whatever is in memory at that location and cast it to an integer.

Also for the languages with out of bounds errors, say we're getting all sibling cells so toward the end of the array we'll be hitting array indices larger than the array size, throwing an error.

Valgrind seems cool, but here we're intentionally getting out of bounds values knowing we're going to filter them out later.
For C, as long as the pointer points to valid memory address sure but you can't assume a valid memory address will result. Behavior is undefined. But I do acknowledge that writing to invalid array indices is a bigger problem than reading from them.
Programming homework and newbie help thread Quote
02-08-2016 , 12:12 PM
Quote:
Originally Posted by ChrisV
Also helpful is using a non prehistoric language that accomplishes these things natively.
Glad to see the language wars are alive and well.*






*Yawn
Programming homework and newbie help thread Quote
02-08-2016 , 02:24 PM
Quote:
Originally Posted by ChrisV
alright, correct me then. dont be the ikestoys of the programming subforum.
I wouldn't know where to start, but it reads more like a bash of all people not using static languages. I don't know who uses error handling as flow control, and I don't know why anyone would think it is "okay" in a duck-typed language while holding it "not okay" in a static language.

Good programming is good programming, and I don't know why you think good programming ideas are tossed out the window just because some don't require explicit types.
Programming homework and newbie help thread Quote
02-08-2016 , 09:26 PM
Quote:
Originally Posted by adios
you can't assume a valid memory address will result. Behavior is undefined.
Alright got it
Programming homework and newbie help thread Quote
02-10-2016 , 04:16 PM
Hi everybody, I am attempting to use the Single Index model to estimate alpha beta and sigma2_ei for 3 stocks and the TSX. Here is my current R code
Importing the Data

setwd("~/Desktop/R Data Sets") Ass2Data1 <- read.csv("~/Desktop/R Data Sets/Ass2DataSheet1.csv") View(Ass2Data1)
Transforming the data into matrix form

b <- as.matrix(Ass2Data1)
Generating Initial Vectors and Matrices

x <- rep(0,60) xx <- matrix(x, ncol=4, nrow=3)
stock <- rep(0,3) alpha <- rep(0,3) beta <- rep(0,3) mse <- rep(0,3) Rbar <- rep(0,3) Ratio <- rep(0,3)
col1 <- rep(0,3) col2 <- rep(0,3) col3 <- rep(0,3) col4 <- rep(0,3) col5 <- rep(0,3)
Regressing each stock on the index and recording results

for(i in 1:3){
alpha[i] <- lm(data=Ass2Data1,formula=Ass2Data1[,1] ~ Ass2Data1[,4]$coefficients[1])
beta[i] <- lm(data=Ass2Data1,formula=Ass2Data1[,2] ~ Ass2Data1[,4]$coefficients[2])
Rbar[i] <- alpha[i]+beta[i]*mean(b[,4])
mse[i] <-sum(lm(data=Ass2Data1,formula=Ass2Data1[,i] ~ Ass2Data1[,4])$residuals2)/(nrow(b)-2)
Ratio[i] <- (Rbar[i]/beta[i])
stock[i] <- i }
xx <- (cbind(stock,alpha,beta,Rbar,mse,Ratio))
However I keep getting the following error messages: Error in Ass2Data1[, 4]$coefficients : $ operator is invalid for atomic vectors
and
Error in beta[i] * mean(b[, 4]) : non-numeric argument to binary operator
If anybody could point me in the right direction with respect to what I'm doing wrong here it would be greatly appreciated.
Programming homework and newbie help thread Quote
02-11-2016 , 08:25 AM
Quote:
Originally Posted by Fishaments
Hi everybody, I am attempting to use the Single Index model to estimate alpha beta and sigma2_ei for 3 stocks and the TSX. Here is my current R code
Code:
#Importing the Data

setwd("~/Desktop/R Data Sets") Ass2Data1 <- read.csv("~/Desktop/R Data Sets/Ass2DataSheet1.csv") View(Ass2Data1)

#Transforming the data into matrix form

b <- as.matrix(Ass2Data1)

#Generating Initial Vectors and Matrices

x <- rep(0,60) xx <- matrix(x, ncol=4, nrow=3)
stock <- rep(0,3) alpha <- rep(0,3) beta <- rep(0,3) mse <- rep(0,3) Rbar <- rep(0,3) Ratio <- rep(0,3)
col1 <- rep(0,3) col2 <- rep(0,3) col3 <- rep(0,3) col4 <- rep(0,3) col5 <- rep(0,3)

#Regressing each stock on the index and recording results

for(i in 1:3){
alpha[i] <- lm(data=Ass2Data1,formula=Ass2Data1[,1] ~ Ass2Data1[,4]$coefficients[1])
beta[i] <- lm(data=Ass2Data1,formula=Ass2Data1[,2] ~ Ass2Data1[,4]$coefficients[2])
Rbar[i] <- alpha[i]+beta[i]*mean(b[,4])
mse[i] <-sum(lm(data=Ass2Data1,formula=Ass2Data1[,i] ~ Ass2Data1[,4])$residuals2)/(nrow(b)-2)
Ratio[i] <- (Rbar[i]/beta[i])
stock[i] <- i }
xx <- (cbind(stock,alpha,beta,Rbar,mse,Ratio))
However I keep getting the following error messages:

Code:
 Error in Ass2Data1[, 4]$coefficients : $ operator is invalid for atomic vectors
and
Code:
Error in beta[i] * mean(b[, 4]) : non-numeric argument to binary operator
If anybody could point me in the right direction with respect to what I'm doing wrong here it would be greatly appreciated.
FYP sort of. Put your code within code tags, properly format within the tags using indents, white space, comment statements to make it readable to others.

Last edited by adios; 02-11-2016 at 08:31 AM.
Programming homework and newbie help thread Quote
02-12-2016 , 05:32 AM
ello mates, I'm working on a C++ console program assignment which is to take a user's weight, height, and age as input, have them select the level of activity in their life, and then computes the number of calories they are burning in a day.

We are to have five choices in activity/exercise levels, and this choice determines the multiplier used in the calculation. I'm using int and I only want to accept five possible input choices, the integers 1-5. I can't quite figure out how to do this input check, so I thought I would post here and ask the smartest people on twoplustwo.

Note: I'm printing the multiplier value for validation/debugging



Code:
#include <iostream>
using namespace std;

main()
{

    double weight = 0.00;
    double height = 0.00;
    double age = 0.00;
    int activityLevel = 0;
    double ALX = 0; //activityLevel multiplier

    cout << "Please enter your weight.\n";
    cin >> weight;
    cout << "Please enter your height.\n";
    cin >> height;
    cout << "Please enter your age.\n";
    cin >> age;

    cout << "Please specify your activity level.\n";
    cout << "1: Sedentary, little or no exercise, desk job.\n";
    cout << "2: Lightly active. (light exercise 1 to 3 times per week.\n";
    cout << "3: Moderately active. (Exercise 3 to 5 times per week.\n";
    cout << "4: Very active. (Exercise 6 to 7 times per week.)\n";
    cout << "5: Extra active.(Heavy exercise, multiple times per day.)\n";
    cin >> activityLevel;    //only 1-5 is valid input 
    

    if (activityLevel == 1)
        ALX = 1.2;
    else if (activityLevel == 2)
        ALX = 1.4;
    else if (activityLevel == 3)
        ALX = 1.6;
    else if (activityLevel == 4)
        ALX = 1.7;
    else if (activityLevel == 5)
        ALX = 1.9;
    if (activityLevel =! 1,2,3,4,5)         //??????????
        cout << "Please only enter numbers 1-5\n";

    cout << ALX << endl;                  // print debug

    return 0;
}




Cheers!

Last edited by catsec; 02-12-2016 at 05:42 AM. Reason: professor requires use of doubles, hence all the doubles
Programming homework and newbie help thread Quote
02-12-2016 , 05:44 AM
The syntax you're looking for is

Code:
if (activityLevel != 1 && activityLevel != 2 && ...)
Or condensing the logic a little, you only need two checks to see if the input is less than 1 or greater than 5, either of which are invalid:

Code:
if (activityLevel < 1 || activityLevel > 5)
However, you can leverage the way if/else checks work to do away with that entirely and replace that entire line with:

Code:
else
The if/else if checks above the validation line already checked to see if it was 1, 2, 3, 4, or 5; adding an "else" case at the end will trigger that code to run if none of the above conditions were satisfied, which in this case means that the user entered an invalid value.
Programming homework and newbie help thread Quote
02-12-2016 , 05:57 AM
goofyballer,

Thanks for your reply mate! I have a couple questions. Does your final example, the mere else, check against other input types like strings and characters? In regards to the middle example, is this relying on the assumption that the user will only enter integers? Will it handle strings and other inputs?

Is the else more secure than the middle one?

I am putting a lot of focus in my studies on secure coding, and I want to make sure I understand very well how to correctly and securely restrict and validate the input of the user.
Programming homework and newbie help thread Quote
02-12-2016 , 06:38 AM
Quote:
Originally Posted by catsec
goofyballer,

Thanks for your reply mate! I have a couple questions. Does your final example, the mere else, check against other input types like strings and characters? In regards to the middle example, is this relying on the assumption that the user will only enter integers? Will it handle strings and other inputs?

Is the else more secure than the middle one?

I am putting a lot of focus in my studies on secure coding, and I want to make sure I understand very well how to correctly and securely restrict and validate the input of the user.
Off the top of my head use encapsulation to write a function the reads user input with a signature something like:

Code:
bool AcceptUserEntry(string & userEntry, size_t maxEntryChars);
Returns false when too many chars entered.

Write another function with a signature something like:


Code:
bool IsUserEntryValid(string userEntry);
Return false for invalid entries.

Then insert calls to those functions in your main routine instead of processing user entries inline. In that way you encapsulate how users enter data and what the criteria is for valid entries. Divide and conquer.
Programming homework and newbie help thread Quote
02-12-2016 , 01:02 PM
one thing I'd recommend is getting the invalid input out of the way first, i.e. "exit early".

e.g.

Code:
if (state is invalid)
  return error;

if (input is a)
  return answer for a;
else if (input is b)
  return answer for b;
else
  return generic answer;
It's more readable imo, and some people agree:
http://programmers.stackexchange.com...n-if-statement
Programming homework and newbie help thread Quote
02-12-2016 , 01:45 PM
Quote:
Originally Posted by catsec
goofyballer,

Thanks for your reply mate! I have a couple questions. Does your final example, the mere else, check against other input types like strings and characters? In regards to the middle example, is this relying on the assumption that the user will only enter integers? Will it handle strings and other inputs?

Is the else more secure than the middle one?

I am putting a lot of focus in my studies on secure coding, and I want to make sure I understand very well how to correctly and securely restrict and validate the input of the user.
Because of how types work in C/C++, activityLevel will always be an integer no matter what the user enters, because it's declared as an int. I forget offhand what the behavior of cin is if the user types a string and you're trying to assign the result to an int, but no matter what the value of activityLevel will still be an integer between a negative very large value and a positive very large value.

There's no difference in security or function (in this context, of course; using "else" isn't always the same as testing if something is <1 or >5) in any of the 3 examples I posted, they just remove redundant checks. Once you've already established in the if/else chain that the value isn't 1, 2, 3, 4, or 5, the only remaining possibility is that it isn't one of those valid values. The code following a naked "else" is a catch all and will execute no matter what if the above conditions are not met.

Because they are logically equivalent, using the "else" in this situation would be preferred due to its flexibility. Say that in the future, you want to remove "5" from valid input. You would delete its line setting activityLevel, and then if you had an "else" at the end your work is done. However, if you had repeated the logic there instead (using "if (activityLevel < 1 || activityLevel > 5)", that logic is no longer correct and would be a bug if you forgot to change the 5 to a 4 there as well. Generally, you want to avoid having the same logic live in multiple places in your code at the same time, because it's difficult to change them all at the same time when requirements change. Leveraging an "else" here is a good way to do that.
Programming homework and newbie help thread Quote
02-16-2016 , 04:48 PM
Hi friends!

i'm trying to implement the Montgomery multiplication in c
https://en.wikipedia.org/wiki/Montgo...multiplication

Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int extendedEuclid(int a, int b, int *x, int *y)	{
    int t, d;
    if (b == 0)	{
        *x = 1; *y = 0; return a;
    }
    d = extendedEuclid(b, a % b, x, y);
    t = *x; *x = *y; *y = t - (a/b)*(*y);
    return d;
}

//inverse of a, mod n
int modInverse(int a, int n)  {
    int x, y;
    extendedEuclid(a, n, &x, &y);
    return (x < 0) ? (x + n) : x;
}

int mont_mul(int N,int p,int x,int y)
{
	int w = modInverse(N,p);
	w= (p-w)&1; //%2

	int bit,u=0;
	int i;
	int k=0;
	for (i=1;i<=x;i=i*2)
	{
		bit = (x>>k)&1;
		u = u+(bit*y);		
		u = (u+ ((u*w)&1)*N);
		u = u>>1; //divide by 2
		k++;
	}

	if (u>=N)
	{
		u=u-N;
	}							

	return u;
}
int main()
{
	int x= 422;
	int y= 421;
	int N= 667; //must be co-prime with b
	int b= 2;
	int p = 1;
	while (p<N)
	{
		p = p*b;
	}

	int p_inverse = modInverse((p-N),N);
	int x_1=(x*p)%N;
	int y_1=(y*p)%N;
	//printf("x1=%d,y1=%d\n",x_1,y_1);
	int r = mont_mul(N,p,x_1,y_1);
	r = (r*p_inverse)%N;
	//r = mont_mul(N,p,r,1);
	int r2 = (x*y)%N;
	printf("%d, %d",r,r2);
	
}
but unfortunately there is a bug where some of the answers I get are right and some are wrong =/, i really can't figure out why, pls help
Programming homework and newbie help thread Quote
02-16-2016 , 07:23 PM
Sounds like it's time to start debugging!

First, you have to dive in and make sure you fully understand what the algorithm is doing and why, or else when you start looking at the values of different variables at different stages of the algorithm, you won't know the significance of what you're looking at.

If you're using an IDE like Visual Studio or something, you can set breakpoints where it will stop execution for you and then there are windows that show you the values of variables. If you're doing it old school, spamming printf() calls everywhere will do the trick.

Basically, you need to be able to trace through your code as it runs, see what it's doing, and compare that to what you would expect it to be doing - and at the point where those two things diverge, that's where you have a bug.

Also, general advice - never put multiple statements on the same line ("t = *x; *x = *y; *y = t - (a/b)*(*y);"), it makes reading code very difficult.
Programming homework and newbie help thread Quote
02-16-2016 , 07:27 PM
Quote:
Originally Posted by CyberShark93
Hi friends!

i'm trying to implement the Montgomery multiplication in c
https://en.wikipedia.org/wiki/Montgo...multiplication

Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int extendedEuclid(int a, int b, int *x, int *y){
    int t, d;
    if (b == 0){
        *x = 1; *y = 0; return a;
    }
    d = extendedEuclid(b, a % b, x, y);
    t = *x; *x = *y; *y = t - (a/b)*(*y);
    return d;
}

//inverse of a, mod n
int modInverse(int a, int n)  {
    int x, y;
    extendedEuclid(a, n, &x, &y);
    return (x < 0) ? (x + n) : x;
}

int mont_mul(int N,int p,int x,int y)
{
int w = modInverse(N,p);
w= (p-w)&1; //%2

int bit,u=0;
int i;
int k=0;
for (i=1;i<=x;i=i*2)
{
bit = (x>>k)&1;
u = u+(bit*y);
u = (u+ ((u*w)&1)*N);
u = u>>1; //divide by 2
k++;
}

if (u>=N)
{
u=u-N;
}

return u;
}
int main()
{
int x= 422;
int y= 421;
int N= 667; //must be co-prime with b
int b= 2;
int p = 1;
while (p<N)
{
p = p*b;
}

int p_inverse = modInverse((p-N),N);
int x_1=(x*p)%N;
int y_1=(y*p)%N;
//printf("x1=%d,y1=%d\n",x_1,y_1);
int r = mont_mul(N,p,x_1,y_1);
r = (r*p_inverse)%N;
//r = mont_mul(N,p,r,1);
int r2 = (x*y)%N;
printf("%d, %d",r,r2);

}
but unfortunately there is a bug where some of the answers I get are right and some are wrong =/, i really can't figure out why, pls help
Is there any rhyme or reason to which inputs produce correct output?

Is the incorrect output always the same with the same input or does it vary?
Programming homework and newbie help thread Quote
02-16-2016 , 08:01 PM
Quote:
Originally Posted by CyberShark93
Hi friends!

i'm trying to implement the Montgomery multiplication in c
https://en.wikipedia.org/wiki/Montgo...multiplication

Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int extendedEuclid(int a, int b, int *x, int *y)	{
    int t, d;
    if (b == 0)	{
        *x = 1; *y = 0; return a;
    }
    d = extendedEuclid(b, a % b, x, y);
    t = *x; *x = *y; *y = t - (a/b)*(*y);
    return d;
}

//inverse of a, mod n
int modInverse(int a, int n)  {
    int x, y;
    extendedEuclid(a, n, &x, &y);
    return (x < 0) ? (x + n) : x;
}

int mont_mul(int N,int p,int x,int y)
{
	int w = modInverse(N,p);
	w= (p-w)&1; //%2

	int bit,u=0;
	int i;
	int k=0;
	for (i=1;i<=x;i=i*2)
	{
		bit = (x>>k)&1;
		u = u+(bit*y);		
		u = (u+ ((u*w)&1)*N);
		u = u>>1; //divide by 2
		k++;
	}

	if (u>=N)
	{
		u=u-N;
	}							

	return u;
}
int main()
{
	int x= 422;
	int y= 421;
	int N= 667; //must be co-prime with b
	int b= 2;
	int p = 1;
	while (p<N)
	{
		p = p*b;
	}

	int p_inverse = modInverse((p-N),N);
	int x_1=(x*p)%N;
	int y_1=(y*p)%N;
	//printf("x1=%d,y1=%d\n",x_1,y_1);
	int r = mont_mul(N,p,x_1,y_1);
	r = (r*p_inverse)%N;
	//r = mont_mul(N,p,r,1);
	int r2 = (x*y)%N;
	printf("%d, %d",r,r2);
	
}
but unfortunately there is a bug where some of the answers I get are right and some are wrong =/, i really can't figure out why, pls help
Looks like modInverse calls extendedEuclid with unitialized (undefined) values and there is a path where those uninitialized values are used in the computation
Programming homework and newbie help thread Quote
02-16-2016 , 08:30 PM
Quote:
Originally Posted by adios
and there is a path where those uninitialized values are used in the computation
Is there? It looks like extendedEuclid is called recursively before x/y are used until b==0, at which point x/y are initialized to 1/0.
Programming homework and newbie help thread Quote
02-16-2016 , 09:09 PM
okay if i never programmed before in my entire life. i have a new idea for an application to using for me. it's a live poker tracker.

it say on app how many hands does your casino average per hour, user?

they'll input dat

then it'll just ask them what they bought in, how much they ended with.

so ultimately it'll give us a visual distribution of hands played x axis number of hands, y would be win/loss.

very simple app that owuld basically just use a database to save their information then plot it. i know a little python i made this which is like the only thing i've ever made which is just a dice gambling game. note i've never worked with databases or visual data modules.

oh on dis what i'm asking is what i'll need to make this compatable for mobile users i don't think i can do python. my dice game is python program but ultimately this 'poker tracker' is what i want to actually publish for other mobile users to use.
Programming homework and newbie help thread Quote
02-16-2016 , 11:16 PM
I imagine there are lots of other apps that already do that, you can just get one of those.

If you are wanting to do it because its a good project to teach yourself coding and making a mobile app, then I would recommend learning java and making it for android. If thats all the functionality you wanted, it wouldnt be very hard and would be a pretty good project in terms of learning.
Programming homework and newbie help thread Quote
02-17-2016 , 02:19 PM
Quote:
Originally Posted by goofyballer
Is there? It looks like extendedEuclid is called recursively before x/y are used until b==0, at which point x/y are initialized to 1/0.
Yep I stand corrected
Programming homework and newbie help thread Quote
02-17-2016 , 10:43 PM
Quote:
Originally Posted by CyberShark93
Hi friends!

i'm trying to implement the Montgomery multiplication in c
https://en.wikipedia.org/wiki/Montgo...multiplication

Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int extendedEuclid(int a, int b, int *x, int *y)	{
    int t, d;
    if (b == 0)	{
        *x = 1; *y = 0; return a;
    }
    d = extendedEuclid(b, a % b, x, y);
    t = *x; *x = *y; *y = t - (a/b)*(*y);
    return d;
}

//inverse of a, mod n
int modInverse(int a, int n)  {
    int x, y;
    extendedEuclid(a, n, &x, &y);
    return (x < 0) ? (x + n) : x;
}

int mont_mul(int N,int p,int x,int y)
{
	int w = modInverse(N,p);
	w= (p-w)&1; //%2

	int bit,u=0;
	int i;
	int k=0;
	for (i=1;i<=x;i=i*2)
	{
		bit = (x>>k)&1;
		u = u+(bit*y);		
		u = (u+ ((u*w)&1)*N);
		u = u>>1; //divide by 2
		k++;
	}

	if (u>=N)
	{
		u=u-N;
	}							

	return u;
}
int main()
{
	int x= 422;
	int y= 421;
	int N= 667; //must be co-prime with b
	int b= 2;
	int p = 1;
	while (p<N)
	{
		p = p*b;
	}

	int p_inverse = modInverse((p-N),N);
	int x_1=(x*p)%N;
	int y_1=(y*p)%N;
	//printf("x1=%d,y1=%d\n",x_1,y_1);
	int r = mont_mul(N,p,x_1,y_1);
	r = (r*p_inverse)%N;
	//r = mont_mul(N,p,r,1);
	int r2 = (x*y)%N;
	printf("%d, %d",r,r2);
	
}
but unfortunately there is a bug where some of the answers I get are right and some are wrong =/, i really can't figure out why, pls help
okay, i found my error, in the loop condition for (i=1;i<=x;i=i*2),
instead of x, it should be the modulus N.

i have got to be the biggest ****** in the history of the universe.
Programming homework and newbie help thread Quote
02-18-2016 , 04:30 AM
Quote:
Originally Posted by goofyballer
Because of how types work in C/C++, activityLevel will always be an integer no matter what the user enters, because it's declared as an int. I forget offhand what the behavior of cin is if the user types a string and you're trying to assign the result to an int, but no matter what the value of activityLevel will still be an integer between a negative very large value and a positive very large value.

goofyballer,

Thanks again for your reply mate!

I'm going to go ahead and post my completed code for this program.

Code:
/* This program takes input from the user and calculates
how many calories they burn per day */

#include <iostream>
using namespace std;

main()
{
    //initialize variables
    double weight = 0.00;                                   //double float variable for user's weight
    double height = 0.00;                                   //double float variable for user's height
    double age = 0.00;                                      //double float variable for user's age
    int activityLevel = 0;                                  //activityLevel variable restricted to integer input
    double ALX = 0.00;                                      //activityLevel multiplier
    double BMR = 0.00;                                      //Basic Metabolic Rate variable
    double DCB = 0.00;                                      //Daily Calories Burned variable

    //prompt user to input details
    cout << "Please enter your weight.\n";
    cin >> weight;
    cout << "Please enter your height.\n";
    cin >> height;
    cout << "Please enter your age.\n";
    cin >> age;

    //prompt user to specify activity level
    cout << "Please specify your activity level.\n";
    cout << "1: Sedentary, little or no exercise, desk job.\n";
    cout << "2: Lightly active. (light exercise 1 to 3 times per week.\n";
    cout << "3: Moderately active. (Exercise 3 to 5 times per week.\n";
    cout << "4: Very active. (Exercise 6 to 7 times per week)\n";
    cout << "5: Extra active. (Exercises two times per day. Includes running marathons, etc.)\n";
    cin >> activityLevel;


    //select multiplier based on user input
    //restrict input to integers 1-5
    if (activityLevel == 1)
        ALX = 1.2;
    else if (activityLevel == 2)
        ALX = 1.4;
    else if (activityLevel == 3)
        ALX = 1.6;
    else if (activityLevel == 4)
        ALX = 1.7;
    else if (activityLevel == 5)
        ALX = 1.9;
    else
        cout << "Please only enter numbers 1-5\n";


    BMR = 66 + (6.2 * weight) + (152.4 * height) - (6.8 * age);                             //BMR calculation
    DCB = ALX * BMR;                                                                        //DCB calculation

    cout << "You burn a total of "<< DCB << " calories each day. " << endl;                 //calculated output

    return 0;
}


When I run the program and enter anything other than an integer or floating point for the double floating point variables such as weight, it jumps to the return and ends the program.

For the integer variable, activityLevel, when I enter a floating point from 1.x to 5.x, it interprets it as just an integer and works properly. If I enter anything other than an integer 1-5, or floating point 1.x-5.x, it jumps to the return and ends the program.



Quote:
Originally Posted by goofyballer
There's no difference in security or function (in this context, of course; using "else" isn't always the same as testing if something is <1 or >5) in any of the 3 examples I posted, they just remove redundant checks. Once you've already established in the if/else chain that the value isn't 1, 2, 3, 4, or 5, the only remaining possibility is that it isn't one of those valid values. The code following a naked "else" is a catch all and will execute no matter what if the above conditions are not met.

Because they are logically equivalent, using the "else" in this situation would be preferred due to its flexibility. Say that in the future, you want to remove "5" from valid input. You would delete its line setting activityLevel, and then if you had an "else" at the end your work is done. However, if you had repeated the logic there instead (using "if (activityLevel < 1 || activityLevel > 5)", that logic is no longer correct and would be a bug if you forgot to change the 5 to a 4 there as well. Generally, you want to avoid having the same logic live in multiple places in your code at the same time, because it's difficult to change them all at the same time when requirements change. Leveraging an "else" here is a good way to do that.

I understand what you're saying, thanks! Question: should I always have the mindset that changes to the code I write will probably need to made at some point in the future, and write my code so that it's easy to change?

Also, could you comment generally regarding how well written and structured and readable my code is?

Cheers!
Programming homework and newbie help thread Quote
Programming homework and newbie help thread
$25m Guaranteed WPM on CoinPoker
Join the action now
Daily Rewards • Splash Pots • CoinRaces
Programming homework and newbie help thread

      
m