if (num2 != 0)
printf("\nInput 3 / Input 2 (int) %12d", divide);
else if (num2 == 0)
printf("\nInput 3 / Input 2 (int) DIV/0");
if (flt4 != 0)
printf("\nInput 2 / Input 1 (double) %16.3f", divide2);
else if (flt4 == 0)
printf("\nInput 2 / Input 1 (double) DIV/0");
When I set num2 or flt4 equal to 0 the program crashes. Otherwise it works perfectly fine. I was looking over the reading about if/else statements and I believe my formatting is correct, but there is obviously an error.
Thanks.
EDIT:
The code where i define divide is:
void calculate (int num1, int num2, int num3, float flt4,int* sum,int* mult,
int* mod,int* divide,double* mult2,double* divide2)
{
*sum = num1 + flt4;
*mult = num1 * num3;
*mod = (num1/10)%10;
*divide= num3 / num2;
*mult2= num1 * flt4;
*divide2= (double)num2 / num1;
return;
}
My question then is, how do I structure this program so if it divides by zero I can display that in the print function.
Most likely you are dividing by zero. The divide variable is set before the 'if' and you perform that operation anyway. Put that inside the first 'if', so it will divide by the num2 iff num2 is different than zero.
Edit:
It should look like that:
if (num2 != 0) {
divide = something / num2;
printf("\nInput 3 / Input 2 (int) %12d", divide);
}
Related
So I'm coding in C and compiling with gcc, I was attempting to create a simple code to display the Fibonacci sequence, you can input the amount of digits of the sequence you'd like to be displayed. Instead of the expected 0 1 1 2 3 5 8 etc. I get 0 1 1 2 3 4 5 6 7 etc. And I can't figure out why, if I remove the second "while" from the code, it works as intended, but I don't understand why. Do variables lose their values if they're inside multiple "while"s? Please help me figure this out. Again I'm a beginner so try to keep it simple.
My code:
#include <stdio.h>
int main()
{
int num, num1 = 0, num2 = 1, cont = 0;
printf("Insert the amount of digits of the Fibonacci sequence you'd like to display: \n");
scanf("%d", &num);
if(num == 1){
printf("%d ", num1);
}
if(num >= 2){
printf("%d ", num1);
printf("%d ", num2);
}
while(cont < num - 2){
num1 = num1 + num2;
printf("%d ", num1);
cont++;
while(cont < num - 2){
num2 = num1 + num2;
printf("%d ", num2);
cont++;
}
}
return 0;
}
The answer to your main question is no. Variables work like this: We declare a variable somewhere in our code. This variable has a name, a value (we either initialize it or it has a random value) and an address in memory. Your program has access to this variable within the block which this variable has been declared. In this particular example, because you declared the variable cont in the main function, that means wherever you change the value of this variable in the main function that change takes place.
The problem in your code is that the variable num1 doesn't change accordingly and, in the whole program, has the value 1. That is the reason why the values printed change by 1. A piece of code that would solve this problem is the following:
#include <stdio.h>
int main()
{
int num, num1 = 0, num2 = 1, cont = 0,temp;
printf("Insert the amount of digits of the Fibonacci sequence you'd like to display: \n");
scanf("%d", &num);
if(num == 1){
printf("%d ", num1);
}
if(num >= 2){
printf("%d ", num1);
printf("%d ", num2);
}
while(cont < num - 2){
temp = num2;
num2 = num1 + num2;
num1 = temp;
printf("%d ", num2);
cont++;
}
return 0;
}
This code just stores the value of num2 in a variable temp, so we don't lose the value of num2 because we want to modify it and the new value of variable num1 must be the old value of variable num2.
#include <stdio.h>
int main()
{
int num1, num2;
printf ("Input value for num1: ");
scanf ("%d", &num1);
printf ("Input value for num2: ");
scanf ("%d", &num2);
int prod =0, i;
for(i = 1; i <= num1; i++){
prod += num2;
}
int quo = 0 , rem = 0;
for(rem = num1 - num2; rem >= 0; rem = rem-num2) {
if(rem < 0)
break;
else
quo++;
}
//The last part is that i need to find the remainder without using multiplication, division and the modulo itself.
printf ("The product of %d and %d is: %d\n", num1, num2, prod);
printf ("The integer quotient of %d and %d is: %d\n", num1, num2, quo);
return 0;
}
The simplest solution for calculating a mod b for positive integers a and b with only subtraction and addition is to subtract b from a until the result is smaller than a. However, this takes many iterations if b is much smaller than a.
A method with better worst-case performance is the following:
#include <stdio.h>
unsigned rem(unsigned a, unsigned b)
{
if(b == 0) return 0; // Error
while(a >= b)
{
unsigned s = b;
do
{
a = a - s;
s = s + s;
} while(a >= s);
}
return a;
}
int main(void)
{
unsigned example = rem(32453, 3);
printf("%u\n", example);
}
This method is based on the fact that to get closer to the result, we can subtract any multiple of b as long as it is smaller than a, so in each inner iteration we try to subtract twice the multiples of the last iteration until the subtractor becomes too large and we start over again with a single multiple of b.
Be aware that this will give wrong results if s = s + s; overflows the unsigned range. Hence, a should not be larger than half the upper limit of unsigned.
If you want a slow calculation of num1 % num2 (i.e. without multiplication/division) you can do:
// Calculate num1 % num2
unsigned rem(unsigned num1, unsigned num2)
{
if (num2 == 0) {.... error handling ....}
while (num1 >= num2) num1 -= num2;
return num1;
}
int main(void)
{
unsigned num1 = 42;
unsigned num1 = 3;
unsigned rem = rem(num1, num2);
printf("%u", rem);
return 0;
}
Using:
Book - C How to Program, 7th edition by Paul Deitel, Harvey Deitel
Codeblocks with mingw as compiler
Language - C
Notes:
Arrays and most operands have not yet been introduced thus far in the book.
Using my code I am returned more than one "smallest is" line or "largest is" line.
I am using this book to teach myself....where are my errors? I am also just starting to learn to code and have chosen C as the language to do this with.
Task:
(Arithmetic, Largest Value and Smallest Value) Write a program that inputs three different
integers from the keyboard, then prints the sum, the average, the product, the smallest and the largest of these numbers. Use only the single-selection form of the if statement you learned in this chapter.
The screen dialogue should appear as follows:
Enter three different integers: 13 27 14
Sum is 54
Average is 18
Product is 4914
Smallest is 13
Largest is 27
This is my code:
#include <stdio.h>
int main(void)
{
int num1;
int num2;
int num3;
printf("Please input three integers.");
scanf("%d%d%d", &num1, &num2, &num3);
printf("Sum is %d\n", num1 + num2 + num3);
printf("Average is %d\n", (num1 + num2 + num3) / 3);
printf("Product is %d\n", num1 * num2 * num3);
if(num1 > num2 && num3) {
printf("Largest is %d\n", num1);
} //end if function
if(num2 > num1 && num3) {
printf("Largest is %d\n", num2);
} //end if function
if(num3 > num1 && num2) {
printf("Largest is %d\n", num3);
} //end if function
if(num1 < num2 && num3) {
printf("Smallest is %d\n", num1);
} //end if function
if(num2 < num1 && num3) {
printf("Smallest is %d\n", num2);
} //end if function
if(num3 < num1 && num2) {
printf("Smallest is %d\n", num3);
} //end if function
}
The condition:
if(num1 > num2 && num3)
means:
if (num1 > num2 && num3 != 0)
or, equivalently, but with a full set of parentheses:
if ((num1 > num2) && (num3 != 0))
You need to write:
if (num1 > num2 && num1 > num3)
Rinse and repeat.
There are better, more compact ways of determining the largest of three integers, such as:
int largest = num1;
int smallest = num1;
if (num2 > largest)
largest = num2;
else if (num2 < smallest)
smallest = num2;
if (num3 > largest)
largest = num3;
else if (num3 < smallest)
smallest = num3;
There are also stunts you can pull with the ternary ?: operator, but you've probably not come across that yet and the stunts don't make for readable code.
You can also use functions to do it:
int num1, num2, num3;
printf("largest number is %d\n", largest(num1, largest(num2, num3)));
printf("smallest number is %d\n", smallest(num1, smallest(num2, num3)));
where largest(int, int) and smallest(int, int) are:
int largest (int a, int b)
{
if (a > b)
return a;
else
return b;
}
and
int smallest (int a, int b)
{
if (a < b)
return a;
else
return b;
}
/* 3/4 of the way down the page I have the code that is listed directly below this paragraph. I need it to print out the remainder, but can not seem to get it right. I know using the Modulus operator is key to this function, but I am lost on how to correctly use it.
result = num1 / num2; /* Division */
printf("When 63 is divided by 6 you get %i\n\n", result);
*/
#include <stdio.h>
int main(void)
{
int num1 = 63;
int num2 = 6;
int result;
float nickels = 0.05;
float pennies = 0.01;
float nickPen; /* I really wasn't sure rather to add nickPen as a float or to even add it at all */
printf("This program will do a few computations with two numbers.\n\n");
printf("The two numbers used by this program are 63 and 6.\n\n");
result = num1 + num2; /* Addition */
printf("The sum of 63 + 6 is %i\n", result);
result = num1 - num2; /* Subtraction */
printf("The difference of 63 - 6 is %i\n", result);
result = num1 * num2; /* Multiplication */
printf("The product of 63 * 6 is %i\n", result);
result = num1 / num2; /* Division */
printf("When 63 is divided by 6 you get %i\n\n", result);
nickPen = nickels*100 + pennies*25; /* Multiplication and addition of money */
printf("If you have 100 nickels + 25 pennies you will have $%.2f\n\n", nickPen);
printf("Thank you for using this program");
getchar();
return 0;
} /* End Main*/
printf("When 63 is divided by 6 the remainder is %i\n\n", 63 % 6);
Modulo in C is x % y where modulo is defined as x - ((int)x/y)*y.
result = num1 % num2; /* Modulus */
printf("When 63 is divided by 6 you get a remainder of %i\n\n", result);
I seem to have a problem with declarations screwing up my math. Any advice or suggestions are highly welcomed.
Here's the code:
int num1, num2, num3, num4, op, ;
op = ((1==num3) || (2==num4));
num3 = (num1 + num2);
num4 = (num1 * num2);
I've been trying lots of arrangements and re-assignments. A lot has compiled, but when 5 + 5 = 2659043, there's a problem...
Not sure what you're trying to do, but this is what your code is doing:
int num1, num2, num3, num4, op, ;
This line informs the C compiler that it needs to allocate space for 5 integers (num1, num2, num3, num4, op), these integers can now be used as variables until the scope expires. Not sure why you have the last ',' you might want to remove that.
op = ((1==num3) || (2==num4));
If num3 is 1, or num4 = 2, then set op to 1 (true). Otherwise, set op to 0 (false).
num3 = (num1 + num2);
Self-explanatory: Add num1 and num2 and put the sum into num3.
num4 = (num1 * num2);
Self explanatory: Multiply num1 and num2 and put the product into num4.
Immediately I see an issue with your program. You are using these variables, but have not initialized them to anything. For example, how is there supposed to be a sum of (num1 + num2) if num1 and num2 do not have a value. Try this:
#include <stdio.h>
int main()
{
int num1, num2, sum;
num1 = 1;
num2 = 2;
sum = num1 + num2;
printf("sum = %d\n", sum);
}
Okay... there's a lot wrong here, but I'll go through what you posted in the comments point by point.
#include <stdio.h>
int main() {
/*Declare the active agents */
int num1=0, num2=0, num3=0, num4=0, op = 1 || 2 ;
You initialize your variables to zero here, except op, which you set to 1 (1 || 2, which is the boolean or, will return 1 (true), so as a result you set op to 1).
num3 = (num1 + num2);
num4 = (num1 * num2);
Here you set num3 and num4 both to zero, since num1 + num2 is 0 + 0 and num1 * num2 is 0 * 0. You want to move this down after your scanf's.
/* Information Extraction Method */
printf("YO MOFO!!!Press a number or hit the dirt!!\n");
scanf("%d", &num1);
printf("Since you didn't hit the dirt, how about another number?\n");
scanf("%d", &num2);
/* Menu (AKA Input */
printf("If you want to add, press 1 ,\nIf you want to multiply, press 2 ... \n\n ");
scanf ("%d", &op);
These printf's and scanf's are good. Good job.
/* PROCESS */
if (op = 1) {num3;};
if (op = 2) {num4;};
Three things here. First, op = 1 is assigning 1 to op. Same with op = 2. You want op == 1 and op == 2 as you have below. The result of this will be that op will always be 2 after these if statements.
The second thing is that, while a valid statement, num3; by itself won't do anything.
Finally, while it doesn't hurt anything, you don't need semicolons after your closing curly braces.
/* OutPut */
if (op == 1) {
printf("Alone, a toothpick is weak, but as part of a sum, your answer is:\n%d"), &num3;
};
if (op == 2) {
printf("Multiplied as a sum of it's parts, your answer is:\n%d"), &num4;
};
Here you're printing out the address of num3 and num4 instead of their values. This is part of the reason you're seeing large numbers that don't make sense, it's the address of num3 and num4 in memory. Only scanf needs the ampersand (&), printf does not. Also, as it stands, the actual value of these will always be 0 since your calculations are done before you get the numbers from the user.
EDIT: Actually, it turns out the reason you aren't getting the right numbers here is that you aren't passing the number to printf at all. You have num3 and num4 outside of the parentheses. There still shouldn't be an ampersand before the variable name, but it should look like this printf("Multiplied... is:\n%d", num4); Notice how num4 is inside the parentheses.
printf("\n\n\n\nMath frum da hud..... Yo. \n\n\nLOL\n >;]");
/* End Of Program */
return 0;
}
Edit: For clarity's sake, I've re-written it in a manner such that it should work the way you intended.
#include <stdio.h>
int main() {
/*Declare the active agents */
int num1=0, num2=0, num3=0, num4=0, op = 0;
/* Information Extraction Method */
printf("YO MOFO!!!Press a number or hit the dirt!!\n");
scanf("%d", &num1);
printf("Since you didn't hit the dirt, how about another number?\n");
scanf("%d", &num2);
num3 = (num1 + num2);
num4 = (num1 * num2);
/* Menu (AKA Input */
printf("If you want to add, press 1 ,\nIf you want to multiply, press 2 ... \n\n ");
scanf ("%d", &op);
/* OutPut */
if (op == 1) {
printf("Alone, a toothpick is weak, but as part of a sum, your answer is:\n%d", num3);
};
if (op == 2) {
printf("Multiplied as a sum of it's parts, your answer is:\n%d", num4);
};
printf("\n\n\n\nMath frum da hud..... Yo. \n\n\nLOL\n >;]");
/* End Of Program */
return 0;
}
HTH.
You did not initialize the variables, so their values are undefined (and probably not 0). You should initialize (like that, for example):
int num1 = 0, num2 = 0, num3 = 0, num4 = 0, op = 0 ;