• 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

Relix

he's Virgin Tight™
I wouldn't recommend PHP since it's kinda amateurish when you compare it to other languages and systems.

There is no "best" IDE, but you can try NetBeans (free) or PHP Storm (not free, I think). For DB, you can probably use MySQL and MySQL Workbench.

If you want to play with PHP w/o actually installing everything at a time, I'd suggest using Uniform Server.

Amateurish in what sense? Thanks for the suggestions though, checking them.
 
I have a question if anyone could answer. For my last HW problem the description reads:
One metric ton is approximately 2205 lbs. Write a program that prompts the user to inputs the amount of rice, in pounds, in a bag. The program outputs the number of bags needed to store one metric ton of rice.

So, here my code:
#include <iostream>
using namespace std;

int main ()
{

double met_ton=2205;
double rice;

cout << "Please, input the amount of rice, in pounds, in a bag " <<endl;
cin >> rice;


double x=met_ton/rice;

if(rice<met_ton)
{cout<< "you need "<< x <<" more bags"<<endl;
}

else(rice>=met_ton);
{cout <<" You've already achieved a one metric ton of rice "<<endl;
}



system("pause");
}


The problem is it runs the else statement fine, but the if statement will return the amount of bags needed, and it also returns the else string. How can I fix this?
 

usea

Member
I have a question if anyone could answer. For my last HW problem the description reads:
One metric ton is approximately 2205 lbs. Write a program that prompts the user to inputs the amount of rice, in pounds, in a bag. The program outputs the number of bags needed to store one metric ton of rice.

The problem is it runs the else statement fine, but the if statement will return the amount of bags needed, and it also returns the else string. How can I fix this?
I don't understand your problem. I also don't think your program satisfies the homework description. The description says to output the number of bags needed to make a ton. You're printing a string which says how many "more" bags you need. It says to output a number. Personally I'd interpret that to mean a whole number, since you can't have part of a bag.

If you enter 10, I'd expect the output to be 221. You need 221 10-pound bags to make 2205 pounds. 220.5 might be acceptable, depends on what the teacher wants.

I don't get the wording in your output. You don't need more bags. And if rice is greater than 2205, the output should be 1.

The question has nothing to do with how much rice you have. It's about how many bags make up a ton.

What's the purpose if the if/else statements in your program? What are they supposed to do?
 
I don't understand your problem. I also don't think your program satisfies the homework description. The description says to output the number of bags needed to make a ton. You're printing a string which says how many "more" bags you need. It says to output a number. Personally I'd interpret that to mean a whole number, since you can't have part of a bag.

If you enter 10, I'd expect the output to be 221. You need 221 10-pound bags to make 2205 pounds. 220.5 might be acceptable, depends on what the teacher wants.

I don't get the wording in your output. You don't need more bags. And if rice is greater than 2205, the output should be 1.

The question has nothing to do with how much rice you have. It's about how many bags make up a ton.

What's the purpose if the if/else statements in your program? What are they supposed to do?

Thanks for the help but I solve it. The problem was I didn't need the condition for the else statement.
 

diaspora

Member
C... C is vexing me. I'm trying to make a program that prints asterix equal to the number the user inputs. i.e. ***** if the user inputs 5, or ** if they put in 2. So I used a for loop.

Code:
#include<stdio.h>

void main()
{
	int num;
	int i;	
	printf("Enter a number:\n");
	scanf("&d",&num);
	
	for(i=0; i<num; i++)
	{
		printf("*",i);
	}
	return;
}

This is giving me an infinite number of asterix. Now if I change it to,

Code:
#include<stdio.h>

void main()
{
	int num;
	int i;	
	printf("Enter a number:\n");
	scanf("&d",&num);
	
	for(i=0; i<num; i++)
	{
		[B]printf("*");[/B]
	}
	return;
}

Same thing happens. Anyone have any feedback for what I've got here?

Now if I change for(i=0; i<num; i++) to for(i=0; i<10; i++) then it works. I get 10 stars, but it won't loop for num number of times input by the user.
 

Kalnos

Banned
scanf("&d",&num);

change that to:

scanf("%d",&num);

(debugger listed 'num' as a being set to a very high negative number which means the for loop would print an infinite number of *)
 

Gartooth

Member
Eclipse is being dumb today...

Code:
void printMe(int *p, int n){
	for(int i = 0; i < n; i++)
		printf("%d ", *(p+i));
	printf("\n");
}

Keep getting an error because it doesn't like that I used a for loop for some reason. It keeps telling me that "for loop initial declarations are only allowed in C99 mode".

Edit: Figured it out, had to put "int i" before the for loop. From there I just use "for(i=0; i<n; i++)".
 
Eclipse is being dumb today...

Code:
void printMe(int *p, int n){
	for(int i = 0; i < n; i++)
		printf("%d ", *(p+i));
	printf("\n");
}

Keep getting an error because it doesn't like that I used a for loop for some reason. It keeps telling me that "for loop initial declarations are only allowed in C99 mode".

Edit: Figured it out, had to put "int i" before the for loop. From there I just use "for(i=0; i<n; i++)".

You can tell Eclipse to use C99 mode if you add the -std=c99 flag to the compiler options, which is in the project preferences, somewhere in the C compiler section.
 

Onemic

Member
How important are limits in C/C++?

Also, is initialization important in C? In my C++ book the author really emphasized the importance of initialization to avoid the possibility of getting junk values, but in my C course I'm taking, no variable that is declared so far gets initialized beforehand.

Lastly, is it possible to create two C++ files within one project and be able to build each one separately? As of right now, whenever I make a new C++ file within a project and try to start it without debugging(ctrl + F5) it will only build the initial C++ file I created when I first made the project.
 

Water

Member
How important are limits in C/C++?
Do you mean numeric limits as in these libraries:
http://en.cppreference.com/w/cpp/header/limits
http://en.cppreference.com/w/cpp/header/climits
Or something else?
Also, is initialization important in C? In my C++ book the author really emphasized the importance of initialization to avoid the possibility of getting junk values, but in my C course I'm taking, no variable that is declared so far gets initialized beforehand.
The C++ author is correct. You should always be mindful of what a variable contains, and usually should not create a variable at all before you can initialize it with a value that makes sense. In C99 it's the exact same thing. In earlier C versions it's only legal to create a variable at the beginning of a block, at which point there may not be any reasonable value to put into it, so that makes it more excusable to have an occasional uninitialized variable hanging around.
Lastly, is it possible to create two C++ files within one project and be able to build each one separately? As of right now, whenever I make a new C++ file within a project and try to start it without debugging(ctrl + F5) it will only build the initial C++ file I created when I first made the project.
"Projects" are specific to Visual Studio, not a C++ feature. VS should be building all the files in the project at the same time; are you sure you have actually added the file into the project? You could also try to "rebuild" the project.
 

Onemic

Member
Do you mean numeric limits as in these libraries:
http://en.cppreference.com/w/cpp/header/limits
http://en.cppreference.com/w/cpp/header/climits
Or something else?
The C++ author is correct. You should always be mindful of what a variable contains, and usually should not create a variable at all before you can initialize it with a value that makes sense. In C99 it's the exact same thing. In earlier C versions it's only legal to create a variable at the beginning of a block, at which point there may not be any reasonable value to put into it, so that makes it more excusable to have an occasional uninitialized variable hanging around.
"Projects" are specific to Visual Studio, not a C++ feature. VS should be building all the files in the project at the same time; are you sure you have actually added the file into the project? You could also try to "rebuild" the project.


I meant something like this:

Code:
// Limits on Arithmetic Expressions
 // limits.c

 int main(void)
 {
         int i, j, ij;
         double x, y, xy;

         printf("Enter an integer : ");
         scanf("%d", &i);
         printf("Enter an integer : ");
         scanf("%d", &j);
         printf("Enter a floating-point number : "); 
         scanf("%lf", &x);
         printf("Enter a floating-point number : ");
         scanf("%lf", &y);

         ij = i * j;
         xy = x * y;

         printf("%d * %d = %d\n", i, j, ij);
         printf("%le * %le = %le\n", x, y, xy); 

         return 0;
 }

And I guess what I mean for the whole projects thing is how is it possible to create multiple C++ files within a project and run them individually? I don't really know all the nuances to visual studio, so I'm at a loss at how to create different files and run them separately without having to create a new project. When I add a file to a project and try to build it, it will either only build the original file or it will give me an error saying that I already have int main present(Pretty sure it's referencing int main within the original file)


And I guess I'll add this question too as I'm having a bit of trouble with it atm. I'm creating a program that takes someones cash and gives back the change in loonies and in cents seperately. The catch is that when printing to console the change in loonies and cents can't be output as a float/double and must instead be output as an int.

Example:

Code:
Enter the number of items : 4
 Enter the unit price      : 3.15
 Purchase price             12.60
 HST (13%)                   1.64
 Total price                14.24

 Cash tendered              20.00
 Change loonies                 5
 Change cents                  76
 

leroidys

Member
I meant something like this:

Code:
// Limits on Arithmetic Expressions
 // limits.c

 int main(void)
 {
         int i, j, ij;
         double x, y, xy;

         printf("Enter an integer : ");
         scanf("%d", &i);
         printf("Enter an integer : ");
         scanf("%d", &j);
         printf("Enter a floating-point number : "); 
         scanf("%lf", &x);
         printf("Enter a floating-point number : ");
         scanf("%lf", &y);

         ij = i * j;
         xy = x * y;

         printf("%d * %d = %d\n", i, j, ij);
         printf("%le * %le = %le\n", x, y, xy); 

         return 0;
 }

And I guess what I mean for the whole projects thing is how is it possible to create multiple C++ files within a project and run them individually? I don't really know all the nuances to visual studio, so I'm at a loss at how to create different files and run them separately without having to create a new project. When I add a file to a project and try to build it, it will either only build the original file or it will give me an error saying that I already have int main present(Pretty sure it's referencing int main within the original file)


And I guess I'll add this question too as I'm having a bit of trouble with it atm. I'm creating a program that takes someones cash and gives back the change in loonies and in cents seperately. The catch is that when printing to console the change in loonies and cents can't be output as a float/double and must instead be output as an int.

Example:

Code:
Enter the number of items : 4
 Enter the unit price      : 3.15
 Purchase price             12.60
 HST (13%)                   1.64
 Total price                14.24

 Cash tendered              20.00
 Change loonies                 5
 Change cents                  76

Check out modf
 

leroidys

Member
Any tips for a student getting started with Java? I have some knowledge with HTML but this is my first programming language.

I know a lot of programs start out with having you make a text adventure in java. Seems like a fun place to start, and would give you motivation to work on something non-trivial.
 

iapetus

Scary Euro Man
Any tips for a student getting started with Java? I have some knowledge with HTML but this is my first programming language.

How are you getting started? What are you following in the way of tutorials/books?

There's an awful load of really bad stuff out there, and we can at least warn you away from that if you're going down the wrong road. :)
 

iapetus

Scary Euro Man
And I guess I'll add this question too as I'm having a bit of trouble with it atm. I'm creating a program that takes someones cash and gives back the change in loonies and in cents seperately. The catch is that when printing to console the change in loonies and cents can't be output as a float/double and must instead be output as an int.

Don't use floats/doubles for currency anyway. Simplest way to do it is probably to store all values internally as an int/long (as appropriate) representing the number of cents. Then you can quickly convert to loonies/cents for display purposes.
 

Azusa

Member
Don't use floats/doubles for currency anyway. Simplest way to do it is probably to store all values internally as an int/long (as appropriate) representing the number of cents. Then you can quickly convert to loonies/cents for display purposes.

Won't be BigDecimal the simplest way to represent money?
 

iapetus

Scary Euro Man
Won't be BigDecimal the simplest way to represent money?

No. :p

Firstly, it looks like he's using C (BigDecimal is a Java thing, isn't it?). Secondly, it's a bit heavyweight compared to just using a simple data type that is fast and easy to carry out operations on.
 

Onemic

Member
Don't use floats/doubles for currency anyway. Simplest way to do it is probably to store all values internally as an int/long (as appropriate) representing the number of cents. Then you can quickly convert to loonies/cents for display purposes.

How can you do that when I need to store the users value for how much cash they gave the cashier? Wouldn't I need to store the value as a float, as the value stored will always have a decimal place.
 

phoenixyz

Member
How can you do that when I need to store the users value for how much cash they gave the cashier? Wouldn't I need to store the value as a float, as the value stored will always have a decimal place.
Assuming you don't need "sub-Cent" precision (e.g. for interest calculation or stuff like that) you can just always use Cent as a unit.
 

tokkun

Member
Could be something like this:

cents: ((int)(doublevalue*100)) % 100

This won't work. In brief, because of binary representation of decimal fractions and the fact the cast always truncates, some values will cause the result to be 1 cent lower than it should be
 

iapetus

Scary Euro Man
How can you do that when I need to store the users value for how much cash they gave the cashier? Wouldn't I need to store the value as a float, as the value stored will always have a decimal place.

You store it in cents. When you read in the value, convert it to cents immediately. When you read in "25.79" as the amount paid, rather than parsing it as a floating point value, parse it as two integer values (25 and 79) then convert that to a single integer value in cents (25 * 100 + 79).
 

Onemic

Member
Code:
	 int changeCents = (((cashTendered - totalPrice) - changeLoonies) * 100);
	 printf("Change in cents: %f\n", changeCents);

	 return 0;

}

Finally found the solution to my problem. I don't even know how I missed something so simple
 
How are you getting started? What are you following in the way of tutorials/books?

There's an awful load of really bad stuff out there, and we can at least warn you away from that if you're going down the wrong road. :)

The book we are following is "Introduction to Java Programming" by Y. Daniel Liang
I was looking for a online program to practice, something similar to CodeAcademy since I did some HTML stuff through there and liked it. But seeing as they only have Java Script I didn't want to learnt that at the same time. I just want to focus on Java for now.
 

Tamanon

Banned
The book we are following is "Introduction to Java Programming" by Y. Daniel Liang
I was looking for a online program to practice, something similar to CodeAcademy since I did some HTML stuff through there and liked it. But seeing as they only have Java Script I didn't want to learnt that at the same time. I just want to focus on Java for now.

Udacity has a Java course that's alright on a foundational level. Also, TheNewBoston.org has a pretty decent Youtube series on it.
 
The book we are following is "Introduction to Java Programming" by Y. Daniel Liang
I was looking for a online program to practice, something similar to CodeAcademy since I did some HTML stuff through there and liked it. But seeing as they only have Java Script I didn't want to learnt that at the same time. I just want to focus on Java for now.

That's the same text I used when I was in college. I thought it was a pretty decent book, it still sits on my desk at work, but I haven't looked at it in years.
 

leroidys

Member
I actually think this is around what I should be doing, as casting is among the things that I'm expected to learn from this assignment. I'm not exactly sure how to implement it though. Here's the incomplete code I have so far:

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

int main(void)
{
	int itemsPurchased;
	float unitPrice;
	float purchasePrice;
	float totalPrice;
	float cashTendered;
	

	 printf("how many items did you buy? ");
	 scanf("%d", &itemsPurchased);
	 printf("What was the Price of each item?");
	 scanf("%f", &unitPrice);

	 purchasePrice = unitPrice * itemsPurchased;
	 printf("That comes to: %0.2f\n", purchasePrice);

	 float HST = 0.13 * purchasePrice;
	 printf("With HST you add: %0.2f\n", HST);

	 totalPrice = HST + purchasePrice;
	 printf("Total purchase price: %0.2f\n", totalPrice);

	 printf("How much money did you give the cashier? ");
	 scanf("%f", &cashTendered);

	 int changeLoonies = cashTendered - totalPrice;
	 printf("Change in loonies: %d\n", changeLoonies);

	 float changeCents = cashTendered - totalPrice;
	 printf("Change in cents: %f\n", changeCents);

	 return 0;

}





ah, I'll try and see if this works.

What do you mean by parse it as two integer values? Sorry, newbie programmer here, so im not up to speed on all the terms. Do you mean have scanf take the input as two integer values? If so, how do you do that?

Read it into a buffer (gets), then you can process it with a for loop.

When you find a '.', replace it with a '\0' null terminator character. Save the index of the period + 1

Now you have buf, which is the null terminated dollar amount, and index + 1, which points to a string of the cent amount. You can then convert them to integers. (strtol || atoi)

That's one way to approach it. It would be a lot clearer if I just wrote it out in psuedocode, but I don't want to do that for obvious reasons.

No matter what your approach though, you should include some error checking on your reads to make sure that the user input is valid.
 
Read it into a buffer (gets), then you can process it with a for loop.

Avoid gets at any and all costs. gets can and will read past the buffer

from the man page

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
 
I need help with making a switch statement for a java program that asks a user to select a shape and it's corresponding values to determine the area and perimeter of said shape. anyways, I tried to write the code like this:

String choice = "";
choice = JOptionPane.showInputDialog( "0:square "+"1:rectangle " + "2:circle " + "3:quit ");

switch(choice)

but when I place choice in those paretheses, it gives me an error. so, how do I turn this
String choice = "";

choice = JOptionPane.showInputDialog( "0:square "+"1:rectangle " + "2:circle " + "3:quit ");


//while answer = 0


while(choice.equals("0")) {
getsq();
calcsq();
dispsq();
choice = JOptionPane.showInputDialog("0:square "+"1:rectangle " + "2:circle " + "3:quit ");
...

if(choice.equals("3")) {
JOptionPane.showMessageDialog(null,"goodbye!");
}

to the switch statement? thanks!
 

leroidys

Member
Avoid gets at any and all costs. gets can and will read past the buffer

from the man page

Yes, thanks for mentioning that. Definitely use fgets or getc. I was just pointing him/her to the manpage for the gets family of functions. (For this assignment gets probably would probably be fine though...)
 

Onemic

Member
Yes, thanks for mentioning that. Definitely use fgets or getc. I was just pointing him/her to the manpage for the gets family of functions. (For this assignment gets probably would probably be fine though...)

I can't use functions though :/

I can only use basic arithmetic/logic operators and casting.
 

usea

Member
I need help with making a switch statement for a java program that asks a user to select a shape and it's corresponding values to determine the area and perimeter of said shape. anyways, I tried to write the code like this:



but when I place choice in those paretheses, it gives me an error. so, how do I turn this


to the switch statement? thanks!
What's the error? I mean, I know what it is because I googled 'java switch string', but reading and understanding the error should be the first step you take when you get one. Also, it helps people understand what problem you're getting. Always, always read the error message.

JOptionPane.showInputDialog returns a string. You can't switch on a string (well, they just added it in the newest java version). So I assume your error message was something relating to not being able to switch on a string.

Why do you have to use a switch statement? Is it part of the assignment? If so, what's the rest of the assignment? You need to include a reasonable amount of information.

Convert the input into an integer. Then switch on that integer. You can use:
Code:
int choiceNumber = Integer.parseInt(choice);
switch(choiceNumber) {
  case 0:
    //blah
    break;
  //etc
}

A far better method would be to create an enum for the shapes and then parse their input to the enum, and switch on that.

Code:
public enum ShapeChoice {
  square,
  rectangle
  circle
  quit
}

String input = JOptionPane.showInputDialog("square, rectangle, circle, quit");
ShapeChoice choice = ShapeChoice.valueOf(input);

switch(choice) {
  case square:
    //whatever
	break;
  case rectangle:
    //a rectangle!
	break;
  //etc
}
 
I need help with making a switch statement for a java program that asks a user to select a shape and it's corresponding values to determine the area and perimeter of said shape. anyways, I tried to write the code like this:



but when I place choice in those paretheses, it gives me an error. so, how do I turn this


to the switch statement? thanks!

What kind of error do you get from the switch statement? Is it a syntax error from the compiler or does it occur during runtime? If it's a compiler error, make sure you're using Java 7, earlier versions don't support switch statements on strings. Is your switch statement of this form:
Code:
switch(choice) {
    case "1": foo(); break;
    case "2": bar(); break:
    case "3": baz(); break;
    default: break;
}
 

leroidys

Member
I can't use functions though :/

I can only use basic arithmetic/logic operators and casting.

Well you can accomplish it by shifting and masking, but it's a pain in the ass. Have you gone over IEEE floating point representation?

You can traverse and parse a string with only arithmetic/logic operators and loops though. You need SOMETHING to read that input. It wouldn't make any sense that you can use scanf and not fgets.
 

Onemic

Member
What about printf? What about scanf?

Everything is a function.

Yup that's fine.

This is an intro to C programming course, so its being taught like everyone is 100% new to programming in general and not just C. Functions have not been introduced yet. Printf and scanf have as they are the most basic of concepts of programming in C.

To give you an idea of this here is the homepage and where we are at(We have only done up to expressions under week 2 and the computations workshop that I'm doing is suggested at the end of the Expressions section)
 

usea

Member
Yup that's fine.

This is an intro to C programming course, so its being taught like everyone is 100% new to programming in general and not just C. Functions have not been introduced yet. Printf and scanf have as they are the most basic of concepts of programming in C.

To give you an idea of this here is the homepage and where we are at(We have only done up to expressions under week 2 and the computations workshop that I'm doing is suggested at the end of the Expressions section)
It was a rhetorical question :)

printf and scanf are not more "basic" of concepts than other functions in their library. If your class allows them, but not other library functions, that's a special thing about your class and not something other people should already understand.
 

Onemic

Member
ah :p

Functions won't be introduced until around week 4, which is why I'm fairly certain they would not expect anyone to use fgets() function or any other library function to be able to solve the problem other than printf, scanf, main(void). 90% of the class doesn't even really know what functions are.
 
Is there a way to translate JAVA to UML Diagrams? Or perhaps software that translate code to UML Diagrams?

Anyone know how to covert .exe, installer back to code and vice versa?
 
Top Bottom