Program returning wrong numbers - c

I am in an intro coding class and I cannot figure out why this program isn't giving me the correct answer and is instead giving me a seemingly random number.
I have tried just putting it as a constant instead of a scanf and it still gives me issues
#include <stdio.h>
const int MIN_CONST = 7;
int ComputeMinutesLost(int userCigarettes) {
int minLost;
int MIN_CONST;
minLost = userCigarettes * MIN_CONST;
return minLost;
}
int main(void) {
int userCigarettes;
printf("How many cigarettes have you smoked?\n");
scanf("%d", &userCigarettes);
printf("You have lost %d minutes to cigarettes. ", ComputeMinutesLost);
return 0;
}
It should just say how many minutes are lost (cigarettes times 7) but it gives a seemingly random number.

Note: The code you posted probably should have flagged you with compile errors, or warnings. Do you have them turned on?
Change the following:
printf("You have lost %d minutes to cigarettes. ", ComputeMinutesLost);
To:
printf("You have lost %d minutes to cigarettes. ", ComputeMinutesLost(userCigarettes));
^------------^ // forgot to include argument
By the way, the numeric value you are seeing is an integer representation of the address of the function ComputeMinutesLost.
Also, (thanks to #unimportant's comment)
in the following code section: //read the comments...
const int MIN_CONST = 7; // one of these...
int ComputeMinutesLost(int userCigarettes) {
int minLost;
int MIN_CONST; // is not necessary, and masks the other
// remove one or the other
// (as is, this one invokes undefined behavior.)

Related

Basic question about how this C code is working

#include <stdio.h>
#include <cs50.h>
int get_pos_int(void);
int main(void) {
int i = get_pos_int();
printf("You entered the positive Integer of %i\n", i);
}
int get_pos_int(void) {
int n;
do {
n = get_int("Insert a positive Integer: ");
}
while(n < 1);
return n;
}
So of course this is just a simple program to test for if a number entered is a number above 0. Out of interest I decided to make this small change to see if it was semantically still correct.
int main(void) {
get_pos_int();
printf("You entered the positive Integer of %i\n", get_pos_int());
}
When running the program with this change, if I input the number '1' it returns me back to the prompt to type an integer, then if I type 1 again it returns 'You entered the positive Integer of 1'
I was just wondering if you could explain what the behaviour is causing this, I like to know why things are working the way they are and it interested me how removing the function being stored in a variable made it behave this way.
Based on your description of what happens, I'm assuming you meant get_pos_int() in your printf.
int i = get_pos_int() stores the return value of the function, not the function itself. So when you made your change, you call the function but discard the value it returns. The function then gets called again in your printf statement. The function being called twice is why you have to enter 1 twice.

Keep getting the same answer when writing a recursive function

Note: I'm fairly new to C programming so I don't know everything just yet.
So I'm working on this assignment for my programming class where I have to write a recursive function count_digits( ) that counts all the digits in a string. I wrote the program and got it to compile but when I type in a number, it always gives me the same answer.
This is what my code is:
#include <stdio.h>
int count_digits(int num)
{
static int count=0;
if(num>0)
{
count++;
count_digits(num/10);
}
else
{
return count;
}
}
int main()
{
int number;
int count=0;
printf("Enter any number:");
scanf("%d",&number);
count=count_digits(number);
printf("\nTotal digits in [%d] are: %d\n",number,count);
return 0;
}
Your non void function returns nothing if num is greater than zero. The compiler should warn you about not returning value. The fix:
return count_digits(num/10);
there are a few things to consider:
What happens if you call your function count_digit() more than one time in the program?
What if you enter 0, 10, 100 as number?
Perhaps you should rethink using a static variable here.
Also for debugging, insert some printfs (or use the debugger) in count_digit() to check how your function behaves.

SIGSEGV Error in short C code

So, as someone who is fairly new to C, I came across my first SIGSEGV Error.
It appeared in a short C program that is meant to be a "guess the number" game. It consists of a self-defined function that compares two numbers and a do-while loop with an input inside it.
The start and the do-while loop:
#include<stdio.h>
int checkNum(int num1, int num2); //See below for explanation
int main(void) {
int input=0, rand=3; //"Random" number has fixed value for testing
do {
printf("Enter number from 0-10: "); //There is not actual range yet
scanf("%d",input); //Get input
} while(checkNum(input, rand)); //Checks if difference != 0
}
The function for comparing:
//Function for comparing input with "random" number
int checkNum(int num1,int num2) { //The two numbers that get compared; First one: input, Second one: "random" rumber
if(num1==num2) {
printf("Correct. The random number was %d",num2);
} else if(num1<num2) {
printf("Wrong. The random number is bigger.");
} else if(num1>num2) {
printf("Wrong. The random number is smaller.");
}
return num2-num1; //Return the difference, leads to 0 if equal
}
I suspect the error to be in the function, caused by a missing use of a pointer, but as far as I understand pointers, they don't seem necessary here: I don't change a single variable in the function, and the return only subtracts two values (which are given I assume).
I hope my error isn't too stupid, and I'd like to thank everyone who can help or tries to.
(I can post my processor values, altough I am not sure if that will help; If any more information is needed for debugging, please tell me)
This:
scanf("%d",input); //Get input
should be:
scanf("%d",&input); //Get input
^^^
Pro tip: always compile with warnings enabled (e.g. gcc -Wall ...) and the compiler will happily point out simple mistakes such as this, saving you a lot of time and grief.

C minimum function always returning 2686916

I am doing a simple function that returns the minimum integer from numbers given from the user(array).
However, it always print 2686916 at the end. Here is my code:
int function()
{
int ar[100];
int i;
int smallest = INT_MAX;
int nums;
int num;
int sum=0;
printf("\nenter array size\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
if (nums <smallest){
smallest=nums;
printf("the smallest %d\n,smallest);
return 0;
}
}
I'm not sure what I'm doing wrong.
My friend, it seems you are new to C, and before you ask questions like this one you should try to follow some tutorials for C. You might try something like this.
If the question you ask is not clear or the code you post won't compile anyway it is very hard to help you out. For now this is all I can do:
int function()
{
int ar[100];
int i;
int smallest = INT_MAX;
int nums = 0; //Always Initialize your variables!
int num = 0;
int sum= 0;
printf("\nenter array size\n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
if (nums <smallest)
{
smallest=nums;
printf("the smallest %d\n",smallest);
}
return 0; //Don't put this in a place that might not be executed!
}
Now it should at least compile, it still doesn't do anything useful as far as I can see. You compare "nums", a variable you didn't use before, with the biggest value of an int, set it to the never used "nums" and print it.
You might want use "sums" or "ar[i]" in the if statement instead, and printing one of these values.(still not 100% sure what you want to do).
Some tips for next time (before you ask a question!):
Variables should always be initialized
In your code you try to use the value of "nums" before it gets a value, this might cause errors or strange results in your code.
Don't put a return in a place that might be skipped,
In your code, "nums" would be bigger than "smallest" (unlikely, bit for example), the code would skip the if statement and never reach the return.
Read your compiler warnings
The code you posted can't compile, read your errors and warnings, and fix them.
(tip) Use better variable names, using names like nums, num and sum make it easy to overlook a mistake.

Pascal's Triangle returning nonsense values

This is a homework project I was assigned some time ago... I've been successful in getting this far on my own, and the only hiccup I have left is (I believe) an issue with data types and overflow.
I've tried changing over to unsigned and double, and the code complies and still accepts input in the terminal, but it seems to hang up after that... nothing is printed and it looks like it's caught in a loop.
Here is the code...
/* pascaltri.c
* A program that takes a single integer as input and returns the nth line of
* Pascal's Triangle. Uses factorial() function to help find items of
* individual entries on a given row.
*/
#include <stdio.h>
#include <stdlib.h>
long factorial(long i)
{
long fact = 1;
while(i > 1)
{
fact = fact * i;
i = i - 1;
}
return fact;
}
main(void)
{
long n;
long *nPtr;
nPtr = &n;
scanf(" %i", nPtr);
if (n >= 0)
{
long k;
long *kPtr;
kPtr = &k;
for(k = 0; k <= n; k++)
{
long ans;
long *ansPtr;
ansPtr = &ans;
ans = factorial(n) / (factorial(k) * factorial(n - k));
printf("\n %i", ans);
}
return 0;
}
return 0;
}
It's not perfect or pretty, but it works up to an input of 13 (that is, row 14) of the triangle. Beyond that I start getting gibberish and even negative values sprinkled throughout the returns... much larger values break the code and return nothing but an exit error message.
Any ideas on how I can correct this problem? I've been staring at the screen for much to long to really see anything myself. Also, it's not essential, but I would like to print my return values on one line, rather than having them separated by a newline character.
1 5 10 10 5 1
Would the easiest way be to load the values into an array as they are computed, and then print the array? Or is there a built-in way I can tell the print statement to occur on only one line?
You are suffering from integer overflow. You may need to find a different approach to the algorithm to avoid having to calculate the large numbers.
In answer to your other point about the newline, you are explicitly printing the newline with the \n in your print statement. Remove it, and you will get answers printed on one line. You probably want to inlucde a final printf("\n"); at the end so the whole line is terminated in a newline.
Some other observations:
You don't need the first return 0; - the control will drop out of
the bottom of the if block and on to the second (should be only)
return 0; and not cause any problems.
You're declaring kPtr but not using it anywhere
You don't need to declare a separate variable nPtr to pass to scanf; you can pass &n directly.
For the garbage, you are most likely running into an integer overflow, that is, your calculated values become too large for the long data type. You should correct it by calculating your factorial function without explicitely calculating n!.
Change scanf(" %i", nPtr); to
scanf(" %ld", nPtr);
and printf("\n %i", ans); to
printf("\n %ld", ans);
to get printout on one line, use:
printf(" %ld", ans);
If you are using gcc, turn on warnings, i.e. use -Wall.

Resources