How do I combine variables into one variable?
I'm making a small calculator program and don't know how to combine the first number, the second number and the opperator into an answer variable
How do I combine variables into one variable?
I'm making a small calculator program and don't know how to combine the first number, the second number and the opperator into an answer variable
well u cant store all these three thing in one single varibale but u can store all these thing in one single string or an arrayOriginally Posted by who_cares
to store that in an array
to store that i a stringCode:arr[0] = val1; arr[1] = op; arr[3] = val2;
NOTE as each element of an string is one byte the val should have one digit number
ssharish2005Code:str[0] = val1; // note val1 should contain one digit not more than that, if u want to store more than one digit its better u go for array ones str[1] = op; str[2] = val2
well, I'm not using but one string. And it is only one char
I have this written: it works untill the line where the answer is declared. I need to combine num_1, opp, and num_2 isto a math problem that will get solved.
Code:/* Name: scanf test Author: who_cares Version 0.0.4 Use: Small calcualtor script, I hope. I don't know much about scanf, or C in general */ #include <stdio.h> int main() { // //vaiables // int num_1, num_2, answer; char opp; //Number 1 printf("Enter the first number:"); scanf("%d", &num_1); //Opperator (+, -, *, /) printf("Enter your operator:"); scanf(" %c", &opp); //Second number printf("Enter the second number:"); scanf("%d", &num_2); //Put it all together answer = num_1 opp num_2; //Print it all out printf("%d %c %d = %d\n", num_1, opp, num_2, answer); }
This:should be done something like this:Code:answer = num_1 opp num_2;
Code:switch ( opp ) { case '+': answer = num_1 + num_2; break; case '-': answer = num_1 - num_2; break; case '*': answer = num_1 * num_2; break; case '/': if ( num_2 ) { answer = num_1 / num_2; } break; }
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
u cant do that, its an error. instead u can choose a better way by using if else statement or and switch case statment which work more effecient for u'r case.Code:answer = num_1 opp num_2;
ssharish2005
okay, I'll have to use a switch then.
I haven't really learned those yet... but I know they're in my book