• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

injurai

Banned
I've seen coursera mentioned a few times here. What exactly is the format of those lessons? Seems you have to enroll over a certain duration? Is it essentially college courses made public? Do they grade stuff?
 

usea

Member
I've seen coursera mentioned a few times here. What exactly is the format of those lessons? Seems you have to enroll over a certain duration? Is it essentially college courses made public? Do they grade stuff?

Yeah usually they have an automated grader built in. You submit assignments and get graded on them. If you have a certain number of points by the end you get a completion certificate.
 

diaspora

Member
Okay, so apparently I lose 50% on my assignment if I can't validate non-numeric input on my assignment which terrifies me. Can anyone point me in the right direction on how that would work for the bolded?

Code:
#include<stdio.h>
#include<ctype.h>

int sectioncode();
int studentnumber();
int main()
{
	// Declare variables.
	int seccode, code, stnum;

	// Get section code.
	seccode = sectioncode();

	// Get Student Number
	stnum = studentnumber();
	
	// Get Marks

	return 0;
}

int sectioncode()
{
	int scode;
	char c = '0';

	do
	{
		printf("Enter the section code (1-4): ");
		scanf("%d", &scode);
		fflush(stdin);		// Flush the buffer so that you don't get infinite looping when entering characters which don't fit the parameters anyway.
	} while (scode < 1 || scode > 4);

	return scode;
}

[B]int studentnumber()
{
	long int stnum, divis, i = 0, zeros = 0;
	
	do
	{
		printf("Enter student number: ");
		scanf("%d",&stnum);
		fflush(stdin);
	}while(stnum < 1 || stnum > 999999999);
	divis = stnum;

	while (divis != 0)
	{
		divis /= 10;
		++i;
	}

	i = 9-i;

	while (zeros < i)
	{
		printf("0");
		zeros++;
	}

	printf("%d", stnum);

	return stnum;
}[/B]

The point of adding the 0s is because the instructions... asked me to if the input is fewer than 9 digits.

EDIT - NVM, NAILED IT
 

Dr_Swales

Member
I need help with C++. The header of a class I'm defining looks like this (I only kept the relevant parts if the following code):

Code:
#ifndef TOOLS_HPP
#define TOOLS_HPP

#include <complex>

using namespace std;

class tools {
    public:
};

#endif

Code:
#include "tools.hpp"

const complex<double> I(0, 1);
const double PI = atan(1)*4;

From the code you have given, all I can see that you have done wrong is you have passed an integer as an argument to atan, which only has definitions for float, double and long double. Either pass 1.0 or typecast your 1 as double(1).
 

diaspora

Member
Code:
#include<stdio.h>
#include<ctype.h>

int sectioncode();
int getstudentnumber();
float getmarks();
void printnum(int studentid);
float getsectionaverage();
int cleanbuffer();
int main()
{
	// Declare variables.
	int seccode, code, stnum;
	float grades;

[B]	// Get section code.
	seccode = sectioncode();

	// Get Student Number
	stnum = getstudentnumber();

	// Get Marks
	grades = getmarks();

	//Print Student Number
	printnum(stnum);[/B]

}

I'm trying to get the bolded to loop until I enter a 0 for seccode. Encapsulating it in a "while(seccode != 0)" ends the loop only after all of the functions execute. I want to terminate it right after entering 0 for seccode. Also, I can't use break or if statements...
 

usea

Member
Code:
#include<stdio.h>
#include<ctype.h>

int sectioncode();
int getstudentnumber();
float getmarks();
void printnum(int studentid);
float getsectionaverage();
int cleanbuffer();
int main()
{
	// Declare variables.
	int seccode, code, stnum;
	float grades;

[B]	// Get section code.
	seccode = sectioncode();

	// Get Student Number
	stnum = getstudentnumber();

	// Get Marks
	grades = getmarks();

	//Print Student Number
	printnum(stnum);[/B]

}

I'm trying to get the bolded to loop until I enter a 0 for seccode. Encapsulating it in a "while(seccode != 0)" ends the loop only after all of the functions execute. I want to terminate it right after entering 0 for seccode. Also, I can't use break or if statements...
Put `seccode = sectioncode();` before the while loop, and then again as the last statement inside of the loop.
 
I'll be taking this, too.

I really liked the previous course, and I didn't even know much about functional programing.

Yeah, I've tried getting into FP before (bought a Lisp book, bought an F# book when I was doing lots of C# stuff, read like 5 different Haskell tutorials) but it never clicked for me until I did this course.

On that note, I'm making a simple raytracer in Scala right now and I'm stuck trying to parallelize it with actors. I've already gotten it to sort of work with a pretty ugly hack (to write to the image, I passed each actor a setPixel: (Int, Int, Color) => () method that is called for every finished pixel) but it randomly decided not to work. (sometimes, the image would be junk, sometimes it would work) Now I want to do it properly by making each actor return his part of the image. Currently, my new approach is like that:
1. Create n actors (where n = number of cores on the machine) in the ParallelRayTracer class
2. Send each actor a Render message, consisting of the scene to render and the part of the output image that he should render (two (Int, Int) pairs with the x/y coordinates of the output image)
3. Once an actor is finished with his job, he sends back a Finished message that stores the start and end coordinates and the rendered data (as an Array[Color])
4. In the ParallelRayTracer class, collect the results in one big Array[Color] (in the right order) and return it as a Future.

Part 4 is where I'm having trouble right now. I want to not block for the results (the Finished messages) from the actors to come in, so I've set up a onSuccess callback that adds the received image data to a buffer. Then I want to sort this buffer by the start indices and convert it into an array.

edit: I fixed it. Future.traverse did the trick, it converts a list of futures into a future of lists. Pretty useful.
 

Onemic

Member
Is it possible to create a for loop condition where the condition is that a number must be divisible by another number?

ie.

Code:
(i = 0; 100 / grossPay; i++)
 
Code:
i = 0; i < (100 / grossPay);  i++

As long as grossPay &#8804; 100 at least. Counting from 0 to less than whatever that ends up being. Is that what you're trying to do?
 

Onemic

Member
Code:
i = 0; i < (100 / grossPay);  i++

As long as grossPay &#8804; 100 at least. Counting from 0 to less than whatever that ends up being. Is that what you're trying to do?

grosspay will always be at least 100 or greater. I want it so that the loop only runs if grosspay is perfectly divisible by 100. (ie 200, 300, 5000, etc.)

Pretty much, my function needs to return the deduction for long term benefits(LBT).LBT is charged at $2 per every full $100 of gross weekly earnings to a maximum LTB payment of $100 per week. An example of a gross weekly pay of $163 will result in a $2 LTB deduction, as there is only one full $100 amount.

This is C btw.
 

usea

Member
Is it possible to create a for loop condition where the condition is that a number must be divisible by another number?

ie.

Code:
(i = 0; 100 / grossPay; i++)

the condition should evaluate to true/false, and should represent a test for whether some number N is divisible by some number Q. The way to do that would be:
`N % Q == 0`

% is the modulo operator. It N % Q divides N by Q, but returns the remainder instead of the result. A remainder of zero means it's divisible.
 
grosspay will always be at least 100 or greater. I want it so that the loop only runs if grosspay is perfectly divisible by 100. (ie 200, 300, 5000, etc.)

Silly me, I somehow missed the second part of your sentence...

Do this \/

the condition should evaluate to true/false, and should represent a test for whether some number N is divisible by some number Q. The way to do that would be:
`N % Q == 0`

% is the modulo operator. It N % Q divides N by Q, but returns the remainder instead of the result. A remainder of zero means it's divisible.
 

Onemic

Member
the condition should evaluate to true/false, and should represent a test for whether some number N is divisible by some number Q. The way to do that would be:
`N % Q == 0`

% is the modulo operator. It N % Q divides N by Q, but returns the remainder instead of the result. A remainder of zero means it's divisible.

I somehow knew the modulo operator would be needed for this, but I just didn't know how it would be applied. Thanks for the tip.
 

Dr_Swales

Member
grosspay will always be at least 100 or greater. I want it so that the loop only runs if grosspay is perfectly divisible by 100. (ie 200, 300, 5000, etc.)

Pretty much, my function needs to return the deduction for long term benefits(LBT).LBT is charged at $2 per every full $100 of gross weekly earnings to a maximum LTB payment of $100 per week. An example of a gross weekly pay of $163 will result in a $2 LTB deduction, as there is only one full $100 amount.

This is C btw.

You say you want to deduct $2 for every $100 in grosspay, why do you need a loop for this?

Just divide grosspay by 100 and deduct this many $2s from the grosspay...

Code:
grosspay -= ((int)grosspay / 100) * 2;

Something like that should do the trick, typecasting the result of the division to an int will discard the values after the decimal point.

You may want to change the code so it is more elegant though =)
 

Onemic

Member
You say you want to deduct $2 for every $100 in grosspay, why do you need a loop for this?

Just divide grosspay by 100 and deduct this many $2s from the grosspay...

Code:
grosspay -= ((int)grosspay / 100) * 2;

Something like that should do the trick, typecasting the result of the division to an int will discard the values after the decimal point.

You may want to change the code so it is more elegant though =)

I can't change the value of the grosspay variable, as I'm using that value for a variety of other functions in my program. Instead the $2 is added to another variable (ltb) that I eventually use to deduct from the gross pay. Here's the function so far:

Code:
double longTermBenefits(double gross) {
    int i;
    int ltb = 0;
    for(i = 0; 100 % gross == 0; i++) {
        ltb + 2;
        if (ltb > 100) {
            break;
        }
    }
    return ltb;

}
 

Onemic

Member
Code:
double longTermBenefits(double gross) {
    int i = gross / 100;
    int ltb = i * 2;
return ltb;
}

Is this what you want?

That wouldn't work as int i doesn't take into account that gross must be perfectly divisible by 100 for the function to do its job properly. As it is right now that function would divide gross by 100 whether it be perfectly divisible or not, (ie gross = 163 would still be used by int i, which in turn would be used by int ltb, to give me 3.26) which would then be used by ltb to multiply it by 2 which I don't want. A $2 deduction should only be applied if the gross is perfectly divisible by 100.
 

Water

Member
That wouldn't work as int i doesn't take into account that gross must be perfectly divisible by 100 for the function to do its job properly. As it is right now that function would divide gross by 100 whether it be perfectly divisible or not, (ie gross = 163 would still be used by int i, which in turn would be used by int ltb, to give me 3.26) which would then be used by ltb to multiply it by 2 which I don't want. A $2 deduction should only be applied if the gross is perfectly divisible by 100.
No, Dr_Swales' code works fine and will only give deductions for full 100s. The truncation that happens when assigning the floating point number into an integer turns the 1.63 into 1.
 

Dr_Swales

Member
That wouldn't work as int i doesn't take into account that gross must be perfectly divisible by 100 for the function to do its job properly. As it is right now that function would divide gross by 100 whether it be perfectly divisible or not, (ie gross = 163 would still be used by int i, which in turn would be used by int ltb, to give me 3.26) which would then be used by ltb to multiply it by 2 which I don't want. A $2 deduction should only be applied if the gross is perfectly divisible by 100.

Ah I misunderstood what you wanted.

I thought you wanted a $2 deduction for every $100. So $100 would be a $2 deduction and $134 would also be a $2 deduction. Where as $264 for example would be a $4 deduction.

Also, you misunderstood my code. Forcing the divide into an int will disregard the decimals. So when gross = 163, i would be 1 because 163/100=1.63, ignore the .63. Then ltb would be 1*2=2.

(Hard to type on a phone!)

EDIT: Thanks Water for explaining while I struggle to type on this.... thing!
 

Onemic

Member
Ah I misunderstood what you wanted.

I thought you wanted a $2 deduction for every $100. So $100 would be a $2 deduction and $134 would also be a $2 deduction. Where as $264 for example would be a $4 deduction.

Also, you misunderstood my code. Forcing the divide into an int will disregard the decimals. So when gross = 163, i would be 1 because 163/100=1.63, ignore the .63. Then ltb would be 1*2=2.

(Hard to type on a phone!)

EDIT: Thanks Water for explaining while I struggle to type on this.... thing!

ah, then that will work. Thanks. Guess I'll see if everything works in a couple of hours when I finish writing my code.
 

Onemic

Member
Ok, so I've hit another wall. I've pretty much finished writing the program with the exception of putting in the arguments for the function that outputs all the calculations. Is there any way to pass a function as an argument or am I not reading instructions right? In my program there are a bunch of functions I need to create that all calculate a different thing, whether that be gross pay for an hourly or salaried worker, deductions through pension plans, etc. All these functions require me to return a value, however, the main function that outputs all the information is supposed to take gross pay as an argument. Problem is, as I said previously, all my functions(except 1 or 2) return a value rather than store them in a variable. So now I don't know what to do as I don't know if I should try passing the functions as an argument(and I'm not even sure if you can do that) or store all calculations the functions make in a variable, but then the potential problem of me not following instructions properly comes back. I also have no idea how to pass a local variable as an argument. Any advice?

EDIT: reading a bit about it on the web and looks like I can't pass the function as an argument based since the function prototype I was provided with(below) does not support a function to be passed as an argument.

Here's a segment of my code that I'm talking about:

Code:
void outputSalaried(int id, double salary, [B]double gross[/B], double ltb, double ei, double cpp, [B]double pTax,double fTax,[/B] int year,int month,int day) {
    double totalDeductions;
    double netPay;
    printf("Kars Payroll Systems\n");
    printf("102 Orfus Road, Downsview ON\n");
    prinf("\n");
    printf("Employee Number %d         ", id);
    printf("For Week Ending: %d\n", payDate);
    printf("\n");
    printf("Salary Paid: %lf\n", annualSalary);
    print("\n");
    printf("GROSS PAY:                                 %lf", gross);
    printf("\n");
    printf("DEDUCTIONS\n");
    printf("Long Term Benefits:                       %lf", longTermBenefits(gross));
    printf("Employment Insurance:                     %lf", employmentInsurance(gross));
    printf("Canada Pension Plan:                      %lf", canadaPensionPlan(gross));
    printf("Provincial Tax:                           %lf", &pTaxPointer);
    printf("Federal Tax:                              %lf", &fTaxPointer);
    printf("\n");
    printf("TOTAL DEDUCTIONS:                         %lf", totalDeductions);
    printf("\n");
    printf("NET PAY:                                  %lf", netPay);

That's the function that outputs all the calculations made in previous functions out to console.

Here are the two gross pay functions(hourly and salaried) I was talking about:
Code:
double grossPaySalaried(double annualSalary) {
    return annualSalary / (1/52);
}

double grossPayHourly(double rate, double numberOfHours) {
    if (numberOfHours > 44) {
        return (rate * 1.5) * numberOfHours;
    }
    else {
        return rate * numberOfHours;
    }

}

My second problem comes with fTax and pTax. My problem stems from the two arguments in outputSalaried coming from a single void function that doesn't return anything. I have no idea how to extract the local variables from the function and pass them as arguments in the outputSalaried function. Here is the function that calculated provincial(pTax) and federal(fTax) taxes.

Code:
void taxes(double gross, double* fTaxPointer, double* pTaxPointer) {
    if(gross % 20000 == 0) {
        *fTaxPointer = gross * 0.16;
        if(gross % 40000 == 0) {
            *fTaxPointer = gross * 0.23;
            if(gross % 60000 == 0) {
                *fTaxPointer = gross * 0.29;
            }
        }
    }
    *pTaxPointer = *fTaxPointer * 0.47;
}

pretty much what I'm supposed to do in this function is to code the body of the function so that it passes back the federal and provincial income tax deductions through the pointers fTaxPointer and pTaxPointer. The tax is calculated as follows:

16% on the first $20,000 earned annually
23% on the next $20,000 earned annually
29% on the remainder earned annually

The Provincial income tax which is collected along with the Federal Tax, is an additional 47% of the Federal tax collected.

Of course I have no idea if my code is even remotely correct or not.
 

Fantastical

Death Prophet
Interview on Tuesday for an internship. Really nervous. Wish me luck!

Honestly, I still get really messed up on recursion, and I know that's going to be asked.
 

maeh2k

Member
No, Dr_Swales' code works fine and will only give deductions for full 100s. The truncation that happens when assigning the floating point number into an integer turns the 1.63 into 1.

While it's well known that the conversion to int cuts off the decimals, personally I'd try to be more clear with the code to really communicate that you want to round down. So I'd recommend using the 'floor' function of math.h to explicitly round down manually.

In this small example it might be overkill, but readability really helps maintainability down the line. Especially if someone else works with the code at some point.
 

maeh2k

Member
My second problem comes with fTax and pTax. My problem stems from the two arguments in outputSalaried coming from a single void function that doesn't return anything. I have no idea how to extract the local variables from the function and pass them as arguments in the outputSalaried function. Here is the function that calculated provincial(pTax) and federal(fTax) taxes.

Code:
void taxes(double gross, double* fTaxPointer, double* pTaxPointer) {
    if(gross % 20000 == 0) {
        *fTaxPointer = gross * 0.16;
        if(gross % 40000 == 0) {
            *fTaxPointer = gross * 0.23;
            if(gross % 60000 == 0) {
                *fTaxPointer = gross * 0.29;
            }
        }
    }
    *pTaxPointer = *fTaxPointer * 0.47;
}

pretty much what I'm supposed to do in this function is to code the body of the function so that it passes back the federal and provincial income tax deductions through the pointers fTaxPointer and pTaxPointer. The tax is calculated as follows:

16% on the first $20,000 earned annually
23% on the next $20,000 earned annually
29% on the remainder earned annually

The Provincial income tax which is collected along with the Federal Tax, is an additional 47% of the Federal tax collected.

Of course I have no idea if my code is even remotely correct or not.

I'll take issue number two, since the first issue doesn't seem quite as clear.

Your code is wrong.
- You call the function with a parameter gross. If gross == 20,001 the program doesn't enter the first if statement. It would have to be exactly 20,000 to get modulo 0. (20001 % 20000 == 1).
- Then you also have to look at the nested ifs. Your gross doesn't change. Gross can't be first 20,000 and then 40,000.
- The two parameters pTax and fTax are output parameters. Because a function can only return one value (here void) this function uses two parameters as outputs (they are pointers, so you can change them from within the function, whereas gross isn't a pointer and you can't change it).
- And then, you don't really calculate the taxes. Lets say someone wants to know the taxes for 45,000. The way this works is:
1. pay 16% for 20,000.
2. pay 23% for 20,000.
3. pay 26% for 5,000.


How about you try that test-driven. I recommend that you write a test for taxes. It will fail. And then you work on taxes till the test is passed.

If you call taxes with gross == 0, gross == 5000, gross == 25000, and gross == 45000, does the function return 0, 0.16 * 5000, 0.16 * 20000 + 0.23 * 5000, and 0.16 * 20000 + 0.23 * 20000 + 0.26 * 5000, respectively?

You can write another function test_taxes somewhere, in which you call taxes with the gross values above and then compare if the output matches.

Eg.

Code:
bool test_taxes()
{
    double pTax = -1;
    double fTax = -1;

    double gross1 = 0;
    double expected1 = 0;

    double gross2 = 5000;
    double expected2 = 0.16 * 5000; 

    double gross3 = 25000;
    double expected3 = 0.16 * 20000 + 0.23 * 5000;

    double gross4 = 45000;
    double expected4 = 0.16 * 20000 + 0.23 * 20000 + 0.26 * 5000;

    taxes(gross1, &fTax, &pTax);
    if(expected1 != fTax)
        return false;

    taxes(gross2, &fTax, &pTax);
    if(expected2 != fTax)
        return false;

    taxes(gross3, &fTax, &pTax);
    if(expected3 != fTax)
        return false;

    taxes(gross4, &fTax, &pTax);
    if(expected4 != fTax)
        return false;
}

(You can extend the test to also account for pTax).

Now turn it into a simple program, where your main function calls test_taxes and nothing else.
Code:
main
    output 'test_taxes'
    bool result = test_taxes()
    output result

And then you work on taxes, till the test passes. (You might want to change test_taxes (e.g. with an additional output to tell you where exactly it failed, or you can even split up test_taxes into four tests (test0gross_taxes, test5000gross_taxes, ...; you could extract a function from test_taxes that takes both gross and the expected value and returns true or false so the code gets less repetitive) and then do the output in your main.
Then you can really start from the bottom and get it to work for the easiest case first and build up from there.

For now, I'll leave it to you to figure out the actual function. But as soon as you have a test up and running it gets a lot easier.
 

Dr_Swales

Member
Interview on Tuesday for an internship. Really nervous. Wish me luck!

Good luck!

... but readability really helps maintainability down the line. Especially if someone else works with the code at some point.

Couldn't agree more, and it is for that reason I would suggest people comment everything when starting to learn how to program. It not only helps you see what you are trying to do but anyone reading your code will be able to help you a lot easier.

Regarding the floor function from math.h; it's another solution that works fine for truncating positive numbers. But do remember that when using floor to truncate negative numbers it will not function as intended and ceil should be used. Not relevant here but it does help to be aware.
 

PowerTaxi

Banned
Hey guys, C is my weakest language and I have an assignment due on Monday.

I have two threads, a reader and a calculator. The reader takes 2 numbers from a file and the calculator adds them. I have to do this using signals. This is what I have so far.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>

FILE *fp;
int int1, int2;

void  
endprog(void *p)
{
	char *q = (char *) p;
	printf("Goodbye from %s\n", q);
}


void *
reader(void * p)
{
	char *n = "Reader Thread";
	pthread_cleanup_push(endprog, (void *)n);
	sigset_t set;
	int sig = SIGUSR1;
	sigemptyset(&set);
	sigaddset(&set, SIGUSR1);
	while(1)
	{
		sigwait(&set, &sig);
		printf ("Thread 1 submitting : " ,"%d %d \n", int1, int2);
	}

	phthread_cleanup_pop(1);
	return ((void *)NULL);
}

void *
calculator(void * p)
{
	char *n = "Calculator Thread";
	pthread_cleanup_push(endprog,(void*) n);
	sigset_t set;
	int sig = SIGUSR1;
	sigemptyset(&set);
	sigaddset(&set, SIGUSR1);
	while(1)
	{
		sigwait(&set, &sig);
		printf ("Thread 2 calculated : ","%d \n", int1 + int2);
	}

	phthread_cleanup_pop(1);
	return ((void *)NULL);
}

int 
main(int argc, char *argv[])
{
	fp= fopen(argv[1], "r");
	if(fp = NULL)
	{
		printf("File doesn't exist\n");
	}
	pthread_t a;
	pthread_t t;
	char *s = "c";
	sigset(SIGUSR1,reader);
	sigset(SIGUSR1,calculator);
	pthread_create(&a, NULL, calculator, (void *)s);
	pthread_create(&t, NULL, reader, (void *)s);
	sleep(1);
	while(1)
	{
		while(fscanf(fp, "%d %d", &int1, &int2)!= EOF)
		{
			
		}
	}

	pthread_cancel(a);
	pthread_cancel(t);
	pthread_join(a,NULL);
	pthread_join(t,NULL);


	fclose(fp);
	return (0);
}

I can't figure out the signal code for main. Any ideas?

Pointing out obvious mistakes will be helpful too.
 

Onemic

Member
I'll take issue number two, since the first issue doesn't seem quite as clear.

Your code is wrong.
- You call the function with a parameter gross. If gross == 20,001 the program doesn't enter the first if statement. It would have to be exactly 20,000 to get modulo 0. (20001 % 20000 == 1).
- Then you also have to look at the nested ifs. Your gross doesn't change. Gross can't be first 20,000 and then 40,000.
- The two parameters pTax and fTax are output parameters. Because a function can only return one value (here void) this function uses two parameters as outputs (they are pointers, so you can change them from within the function, whereas gross isn't a pointer and you can't change it).
- And then, you don't really calculate the taxes. Lets say someone wants to know the taxes for 45,000. The way this works is:
1. pay 16% for 20,000.
2. pay 23% for 20,000.
3. pay 26% for 5,000.


How about you try that test-driven. I recommend that you write a test for taxes. It will fail. And then you work on taxes till the test is passed.

If you call taxes with gross == 0, gross == 5000, gross == 25000, and gross == 45000, does the function return 0, 0.16 * 5000, 0.16 * 20000 + 0.23 * 5000, and 0.16 * 20000 + 0.23 * 20000 + 0.26 * 5000, respectively?

You can write another function test_taxes somewhere, in which you call taxes with the gross values above and then compare if the output matches.


And then you work on taxes, till the test passes. (You might want to change test_taxes (e.g. with an additional output to tell you where exactly it failed, or you can even split up test_taxes into four tests (test0gross_taxes, test5000gross_taxes, ...; you could extract a function from test_taxes that takes both gross and the expected value and returns true or false so the code gets less repetitive) and then do the output in your main.
Then you can really start from the bottom and get it to work for the easiest case first and build up from there.

For now, I'll leave it to you to figure out the actual function. But as soon as you have a test up and running it gets a lot easier.



I've been testing the function and just been coming up cold. It seems that my more immediate problem with the function is that *ftaxpointer/ *ptaxpointer keeps equating to 0.00000 when I output the function to console. I tried using your test example, but couldn't use it due to there being multiple returns within a single function(the compiler would just keep giving me errors) so I made a little program that only runs the taxes function, so I could play around with it that way. Here's my code



Code:
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS

void taxes(double gross, double* fTaxPointer, double* pTaxPointer) {
    if(gross >= 20000) {
        printf("printing first set\n");
        *fTaxPointer = gross * 0.16;
        printf("ftax is %lf\n", fTaxPointer);
        if(gross >= 40000) {
            printf("printing second set\n");
            *fTaxPointer = gross * 0.23;
            printf("ftax is %lf\n", fTaxPointer);
            if(gross >= 60000) {
                printf("printing third set\n");
                *fTaxPointer = gross * 0.29;
                printf("ftax is %lf\n", fTaxPointer);
            }
        }
    }
    printf("printing ptax\n");
    *pTaxPointer = *fTaxPointer * 0.47;
    printf("ptax is %lf", pTaxPointer);
}

int main(void)
{
    double gross = 65000;
    double ftax = 0;
    double ptax = 0;
    printf("test taxes\n");

    taxes(gross, &ftax, &ptax);

    return 0;
}

Any reason as to why this is the case?

of course, it must be obvious by now that pointers are my worst enemy.
 

Dr_Swales

Member
Any reason as to why this is the case?

of course, it must be obvious by now that pointers are my worst enemy.

You forgot to dereference your pointers, fTaxPointer and pTaxPointer should be *fTaxPointer and *pTaxPointer. The way it is at the moment you are just outputting the address stored by the pointer.


Have you been given these function prototypes and you have to fill in the function body?
 

Onemic

Member
You forgot to dereference your pointers, fTaxPointer and pTaxPointer should be *fTaxPointer and *pTaxPointer. The way it is at the moment you are just outputting the address stored by the pointer.


Have you been given these function prototypes and you have to fill in the function body?

Thanks, that did the trick....stupid pointers.


Yup, I've been given all the function prototypes needed to make the program. I just need to fill in the body of the code.

btw, is there some type of reference I can access/buy that goes more indepth with pointers and explains how they work. I thought taking the C class would help, but I'm just as confused with pointers as when I was trying to teach myself them in C++.
 

maeh2k

Member
of course, it must be obvious by now that pointers are my worst enemy.

Since the pointers are just output parameters you could also work with local variable if you want. Just use a double fresult, presult. Then at the very end of the function you assign the values to the pointers *pTax = presult;

Your function still doesn't work. Try to calculate the value in your head following your function and you'll see. Note how you just assign a value to your result in a single line for every if statement. What you are doing is, you take the gross, look up one tax rate, and use that rate for the entire gross. What you want, is to tax the first 20,000 different than the rest. So one assignment doesn't cut it.

Maybe try to write the function in pseudo-code and post it here. With pseudo-code you don't get distracted by pointers and stuff.
 

Onemic

Member
Ok, I think I have it down now after re-reading what I need to do. Using 45000 as the argument for gross, it looks like I'm getitng the correct values I should be getting, unless I'm reading what I need to do wrong again :/

Code:
void taxes(double gross, double* fTaxPointer, double* pTaxPointer) {
//using 45000 as an argument for gross
    if(gross >= 20000) {
        printf("printing first set\n");
        *fTaxPointer = 20000 * 0.16;
        printf("ftax is %lf\n", *fTaxPointer); // ftax = 3200
        if(gross >= 40000) {
            printf("printing second set\n");
            *fTaxPointer += 20000 * 0.23; // ftax = 7800
            printf("ftax is %lf\n", *fTaxPointer);
            if(gross > 40000) {
                printf("printing third set\n");
                *fTaxPointer += (gross - 40000) * 0.29; // ftax = 9250
                printf("ftax is %lf\n", *fTaxPointer);
            }
        }
    }
    printf("printing ptax\n");
    *pTaxPointer = *fTaxPointer * 0.47; //ptax = 4347.5
    printf("ptax is %lf\n", *pTaxPointer);
}

int main(void)
{
    double ftax = 0;
    double ptax = 0;
    printf("test taxes\n");

    taxes(45000, &ftax, &ptax);
    return 0;
}
 

maeh2k

Member
Ok, I think I have it down now after re-reading what I need to do. Using 45000 as the argument for gross, it looks like I'm getitng the correct values I should be getting, unless I'm reading what I need to do wrong again :/

Code:
void taxes(double gross, double* fTaxPointer, double* pTaxPointer) {
//using 45000 as an argument for gross
    if(gross >= 20000) {
        printf("printing first set\n");
        *fTaxPointer = 20000 * 0.16;
        printf("ftax is %lf\n", *fTaxPointer); // ftax = 3200
        if(gross >= 40000) {
            printf("printing second set\n");
            *fTaxPointer += 20000 * 0.23; // ftax = 7800
            printf("ftax is %lf\n", *fTaxPointer);
            if(gross > 40000) {
                printf("printing third set\n");
                *fTaxPointer += (gross - 40000) * 0.29; // ftax = 9250
                printf("ftax is %lf\n", *fTaxPointer);
            }
        }
    }
    printf("printing ptax\n");
    *pTaxPointer = *fTaxPointer * 0.47; //ptax = 4347.5
    printf("ptax is %lf\n", *pTaxPointer);
}

int main(void)
{
    double ftax = 0;
    double ptax = 0;
    printf("test taxes\n");

    taxes(45000, &ftax, &ptax);
    return 0;
}

Getting better. However, so far you only really cover gross values over 40,000. Eg. if you input 0 everything goes horribly wrong. Or if you input 26,000, you use the right tax rate for the first 20,000, but don't consider the remaining 6,000 for the higher tax rate.

Try using the test code I posted at first. I think it may be a pure-C issue that you can only have one return statement. In this case it doesn't much matter.

Code:
bool test_taxes(gross, expected)
{
    double pTax = -1;
    double fTax = -1;

    taxes(gross, &fTax, &pTax);
    return (expected == fTax)
}

And then you can run the specific tests in your main:
- test_taxes(0, 0)
- test_taxes(5000, 0.16 * 5000)
- test_taxes(25000, 0.16 * 20000 + 0.23 * 5000)
- test_taxes(45000, 0.16 * 20000 + 0.23 * 20000 + 0.26 * 5000)

For each test you can output if it returns true or false.
 

Onemic

Member
Getting better. However, so far you only really cover gross values over 40,000. Eg. if you input 0 everything goes horribly wrong. Or if you input 26,000, you use the right tax rate for the first 20,000, but don't consider the remaining 6,000 for the higher tax rate.

Try using the test code I posted at first. I think it may be a pure-C issue that you can only have one return statement. In this case it doesn't much matter.

Code:
bool test_taxes(gross, expected)
{
    double pTax = -1;
    double fTax = -1;

    taxes(gross, &fTax, &pTax);
    return (expected == fTax)
}

And then you can run the specific tests in your main:
- test_taxes(0, 0)
- test_taxes(5000, 0.16 * 5000)
- test_taxes(25000, 0.16 * 20000 + 0.23 * 5000)
- test_taxes(45000, 0.16 * 20000 + 0.23 * 20000 + 0.26 * 5000)

For each test you can output if it returns true or false.

Ah, I think you may be getting the requirements messed up. The first rate is only to be applied when the gross pay reaches 20k, the second when it reaches 40k and the third if the gross is anything over 40k. Therefore if the gross pay is something like 25k, only the first rate will be applied and not the third. Same with a gross pay of 5k. In that situation, no rate would be applied. I still want to try doing your method though, but I'll try it once this program is finally completed.

At this point I'm almost ocmpletely done, but it seems that I've run into one final snag. All my functions output perfectly except my taxes function. For some reason if I pass the variable 'gross' as an argument(the variable gross equals to grossPayHourly function, which returns the gross value) pTax and fTax output 0.00000 instead of the correct value. However if I pass a random number, say 70000 as an arguments instead, fTax and pTax both output their correct values. Any idea why this is happening?

Code:
//tax function

void taxes(double gross, double* fTaxPointer, double* pTaxPointer) {
    if(gross >= 20000) {
        *fTaxPointer = 20000 * 0.16;
        if(gross >= 40000) {
            *fTaxPointer += 20000 * 0.23;
            if(gross > 40000) {
                *fTaxPointer += (gross - 40000) * 0.29;
            }
        }
    }
    *pTaxPointer = *fTaxPointer * 0.47;
}


//output function

void outputHourly(int id, double rate, double hours, double gross, double ltb, double ei,double cpp, double pTax,double fTax,int year,int month,int day) {
    double totalDeductions;
    double netPay;
    printf("Chidi Payroll Systems\n");
    printf("102 Orfus Road, Downsview ON\n");
    printf("\n");
    printf("Employee Number %d         ", id);
    printf("For Week Ending: %d/%d/%d\n", year, month, day);
    printf("\n");
    printf("Hourly Rate:    %0.2lf        ", rate);
    printf("Hours Worked:    %0.2lf\n", hours);
    printf("\n");
    printf("GROSS PAY:                                    %0.2lf\n", gross);
    printf("\n");
    printf("DEDUCTIONS:\n");
    printf("Long Term Benefits:                             %0.2lf\n", ltb);
    printf("Employment Insurance:                           %0.2lf\n", ei);
    printf("Canada Pension Plan:                            %0.2lf\n", cpp);
    printf("Provincial Tax:                               %0.2lf\n", pTax);
    printf("Federal Tax:                                  %0.2lf\n", fTax);
    printf("\n");
    printf("TOTAL DEDUCTIONS:                             %0.2lf\n", totalDeductions);
    printf("\n");
    printf("NET PAY:                                      %0.2lf\n", netPay);

}


//calling tax function and output function

double fTaxH = 0;
double pTaxH = 0;
taxes(hGross, &fTaxH, &pTaxH);
printf("ftax is %lf", fTaxH); //test to make sure ftax/ptax output there correct values
printf("pTax is %lf", pTaxH); //currently both pTax and fTax evaluate to 0.0000
outputHourly(id, rate, hours, hGross, ltbH, eiH, cppH, pTaxH, fTaxH, year, month, day);
 

maeh2k

Member
Ah, I think you may be getting the requirements messed up.

You might be right, but I'd still very much recommend testing the function. It really helps during development and gives you the confidence that the function works.
E.g. when you use a value < 20,000, you don't enter the if-statement, you never initialize fTax to 0 and just work with whatever value happens to be in fTax.



At this point I'm almost ocmpletely done, but it seems that I've run into one final snag. All my functions output perfectly except my taxes function. For some reason if I pass the variable 'gross' as an argument(the variable gross equals to grossPayHourly function, which returns the gross value) pTax and fTax output 0.00000 instead of the correct value. However if I pass a random number, say 70000 as an arguments instead, fTax and pTax both output their correct values. Any idea why this is happening?

That's also a case where testing might help. If you test the taxes function properly, then you get the confidence that it's not causing this issue. In that case maybe prossPayHourly does something wrong.
 
Hey, I'm popping in to ask a question since I'm curious. Anyone have any opinions on JES and/or Jython?
From what I can tell it's just a learning language based in python running in a Java virtual machine, but with a lot of built-in functions to reduce overhead. I think it's obviously not viable to complete tasks outside from within the IDE, but I just wanna hear opinions on it if anyone has any.
 

Slavik81

Member
46% on my C assignment is the second failing mark I've received so far. I should probably just drop programming...
Its normal to have trouble getting started. It requires a completely different way of thinking than most people are used to.

It's quite possible to fail miserably the first few times you try but still eventually find success. Not that you necessarily will, but failing a few assignments (or even a course) isn't something to despair over.

Introductory programming courses tend to have very high failure rates.
 

diaspora

Member
Its normal to have trouble getting started. It requires a completely different way of thinking than most people are used to.

It's quite possible to fail miserably the first few times you try but still eventually find success. Not that you necessarily will, but failing a few assignments (or even a course) isn't something to despair over.

Introductory programming courses tend to have very high failure rates.

TBH, it's alot easier reading my C++ For Dummies book talk about constructors through the lens of cars or squirrels than "val"s or "ival"s.
 

rodvik

Member
46% on my C assignment is the second failing mark I've received so far. I should probably just drop programming...

if you can get into the habit of making yourself little apps in your spare time it will help hugely. Just the practice of programming in a language really helps. Its tough to try and get a good grade by just doing the course work imho.
 
Ugh does anyone here know a good tutorial for implementing an RSS reader into android project?

This is a good tutorial for a Java RSS reader, using the java.xml functionality (since RSS files are just XML). I used that one to make a simple RSS parser with JSF a few months ago and it worked well. The rest would be Android specific stuff, basically just wiring the RSS model to the UI (if that's all you want to do). Note that this tutorial requires Java 7 since it uses a switch statement on strings.
 
Top Bottom