Here is the problem: The game Totals can be played by any number of people. It starts with a total of 100 and each player in turn makes an integer displacement between -20 and 20 to that total. The winner is the player whose adjustment makes the total equal to 5. Using only the three variables given:
total
adjustment
counter
Here is what I have so far:
#include <stdio.h>
int main (void)
{
int counter=0;
float adj;
int ttl=100;
printf("You all know the rules now lets begin!!!\n\n\nWe start with 100. What is\n");
while (ttl!=5)
{
printf("YOUR ADJUSTMENT?");
scanf("%f",&adj);
counter++;
if (adj<=20 && adj>=-20)
{
ttl=ttl+adj;
printf("The total is %d\n",ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
printf("The game is won in %d steps!",counter);
}
What I need:
When a decimal number is entered it goes to the else. How do I determine if a float has a fractional part.
You can cast the float to an int and then compare it to your original variable. If they are the same there was no fractional part.
By using this method, there is no need for a temporary variable or a function call.
float adj;
....
if (adj == (int)adj)
printf ("no fractional!\n");
else
printf ("fractional!\n");
Explanation
Since an int cannot handle fractions the value of your float will be truncated into an int (as an example (float)14.3 will be truncated into (int)14).
When comparing 14 to 14.3 it's obvious that they are not the same value, and therefore "fractional!" will be printed.
#include <stdio.h>
#include <math.h>
int main ()
{
float param, fractpart, intpart;
param = 3.14159265;
fractpart = modff (param , &intpart);
return 0;
}
http://www.cplusplus.com/reference/clibrary/cmath/modf/
modff finds the fractional part, so I guess testing whether it's equal to 0 or null will answer your question.
if you want to know whether a real number x has no fractional part, try x==floor(x).
I am only learning C so tell me if I am wrong, please.
But if instead of using
scanf("%f",&adj);
if you use:
scanf("%d%d", &adj, &IsUndef);
Therefore if the user typed anything other than a whole integer &IsUndef would not equal NULL and must have a fractional part sending the user to else.
maybe.
Using scanf() is problematic. If the user typed -5 +10 -15 -15 on the first line of input, then hit return, you'd process the 4 numbers in turn with scanf(). This is likely not what you wanted. Also, of course, if the user types +3 or more, then the first conversion stops once the space is read, and all subsequent conversions fail on the o or or, and the code goes into a loop. You must check the return value from scanf() to know whether it was able to convert anything.
The read-ahead problems are sufficiently severe that I'd go for the quasi-standard alternative of using fgets() to read a line of data, and then using sscanf() (that extra s is all important) to parse a number.
To determine whether a floating point number has a fractional part as well as an integer part, you could use the modf() or modff() function - the latter since your adj is a float:
#include <math.h>
double modf(double x, double *iptr);
float modff(float value, float *iptr);
The return value is the signed fractional part of x; the value in iptr is the integer part. Note that modff() may not be available in compilers (runtime libraries) that do not support C99. In that case, you may have to use double and modf(). However, it is probably as simple to restrict the user to entering integers with %d format and an integer type for adj; that's what I'd have done from the start.
Another point of detail: do you really want to count invalid numbers in the total number of attempts?
#include <stdio.h>
#include <math.h>
int main(void)
{
int counter=0;
int ttl=100;
printf("You all know the rules now lets begin!!!\n"
"\n\nWe start with 100. What is\n");
while (ttl != 5)
{
char buffer[4096];
float a_int;
float adj;
printf("YOUR ADJUSTMENT?");
if (fgets(buffer, sizeof(buffer), stdin) == 0)
break;
if (sscanf("%f", &adj) != 1)
break;
if (adj<=20 && adj>=-20 && modff(adj, &a_int) == 0.0)
{
counter++; // Not counting invalid numbers
ttl += adj;
printf("The total is %d\n", ttl);
}
else
{
printf ("I'm sorry. Do you not know the rules?\n");
}
}
if (ttl == 5)
printf("The game is won in %d steps!\n", counter);
else
printf("No-one wins; the total is not 5\n");
return(0);
}
Clearly, I'm studiously ignoring the possibility that someone might type in more than 4095 characters before typing return.
Related
I couldn't share the original code but the below program is as similar to my problem.
#include<stdio.h>
#include<conio.h>
void clrscr(void);
int reverse_of(int t,int r)
{
int n=t;
r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n",n); /*displays the input*/
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
return r; /*returns the value to main function*/
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
};
int main()
{
int n,r;
void clrscr();
printf("Enter a number: ");
scanf("%d",&n);
//while (n!=0) /*Use this for any number of digits*/
/* {
int z=n%10;
r=r*10+z;
n=n/10;
} */
r=reverse_of(n,r);
printf("The reverse of your number is: %d\n",r);
return 0;
};
This program displays the reverse of a 4 digit number. it works perfect when my first input is a 4 digit number. The output is as below.
(Keep in mind that i dont want this program to display the reverse of
a number unless its 4 digit)
Enter a number: 1234
Your number is: 1234
The reverse of your number is: 4321
Now when i give a non 4 digit number as the first input the program displays that it is not a 4 digit number and asks me for a 4 digit number. Now when i give a 4 digit number as the second input. It returns the correct answer along with another answer which is supposed to be the answer for the first input. (since the program cannot find the reverse value of a non 4 digit number the output always return 0 in that particular case). If i give 5 wrong inputs it displays 5 extra answers. Help me get rid of this.
Below is the output when i give multiple wrong inputs.
Enter a number: 12
The number you entered is 2 digit so please enter a four digit number
Enter a number: 35
The number you entered is 2 digit so please enter a four digit number
Enter a number: 455
The number you entered is 3 digit so please enter a four digit number
Enter a number: 65555
The number you entered is 5 digit so please enter a four digit number
Enter a number: 2354
Your number is: 2354
The reverse of your number is: 4532
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
The reverse of your number is: 0
Help me remove these extra outputs btw im using visual studio code and mingw compiler.
The problem lies here:
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n",count);
main();
}
You're calling main() from reverse_of().
Try replacing the main(); with return 0; and in main(), do this:
int n,r;
do{
printf("Enter a number: ");
scanf("%d",&n);
r=reverse_of(n,r);
}while(r==0);
printf("The reverse of your number is: %d\n",r);
This happens because of the multiple recursion caused by the call of main() inside of the reverse_of function.
To avoid such thing you can move the printf("The reverse of your number is: %d\n", r); to the inside of the if(count==4){} and your problem is solved!
Also, note that your reverse_of functions does not need to receive the int r, instead it can be written like this:
#include <stdio.h>
int reverse_of(int t)
{
int n = t;
int r = 0;
int count = 0;
while (t != 0) /*Loop to check the number of digits*/
{
count++;
t = t / 10;
}
if (count == 4) /*if it is a 4 digit number then it proceeds*/
{
printf("Your number is: %d \n", n); /*displays the input*/
while (n != 0) /*This loop will reverse the input*/
{
int z = n % 10;
r = r * 10 + z;
n = n / 10;
}
printf("The reverse of your number is: %d\n", r);
return 1;
}
else /*This will execute when the input is not a 4 digit number */
{
printf("The number you entered is %d digit so please enter a four digit number \n", count);
return 0;
}
};
int main()
{
int n, r=0;
while (r!=1){
printf("Enter a number: ");
scanf("%d", &n);
r=reverse_of(n);
}
return 0;
};
Hope it helped!
Well, your program has some ambiguity: If you stop as soon as you get 0, then the reverse of 1300, 130 and 13 will be the same number, '31'.
So, first of all you need two parameters in your function, to deal with the number of digits you are considering, so you don't stop as soon as the input number is zero, but when all digits have been processed. Then you extract digits from the least significant, and add them to the result in the least significant place. This can be done with this routine:
int reverse_digits(int source, int digits, int base)
{
int i, result = 0;
for (i = 0; i < digits; i++) {
int dig = source % base; /* extract the digit from source */
source /= base; /* shift the source to the right one digit */
result *= base; /* shift the result to the left one digit */
result += dig; /* add the digit to the result on the right */
}
return result;
}
The extra parameter base will allow you to operate in any base you can represent the number. Voila!!!! :)
#include <stdio.h>
int main()
{
int src;
while (scanf("%d", &src) == 1) {
printf("%d => %d\n",
src,
reverse_digits(src, 5, 10));
}
}
will provide you a main() to test it.
In contrast to C++, in C, it is allowed to call main recursively. But it is still not recommended. There are only a few situations where it may be meaningful to do this. This is not one of them.
Recursion should only be used if you somehow limit the depth of the recursion, otherwise you risk a stack overflow. In this case, you would probably have to call the function main recursively several thousand times in order for it to become a problem, which would mean that the user would have to enter a value that is not 4 digits several thousand times, in order to make your program crash. Therefore, it is highly unlikely that this will ever become a problem. But it is still bad program design which may bite you some day. For example, if you ever change your program so that it doesn't take input from the user, but instead takes input from a file, and that file provides bad input several thousand times, then this may cause your program to crash.
Therefore, you should not use recursion to solve this problem.
The other answers have solved the problem in the following ways:
This answer solves the problem by making the function reverse_of not return the reversed value, but to instead directly print it to the screen, so that it does not have to be returned. Therefore, the return value of the function reverse_of can be used for the sole purpose of indicating to the calling function whether the function failed due to bad input or not, so that the calling function knows whether the input must be repeated. However, this solution may not be ideal, because normally, you probably want the individual functions to have a clear area of responsibility. To achieve this clear area of responsibility, you may want the function main to handle all the input and output and you may want the function reverse_of to do nothing else than calculate the reverse number (or indicate a failure if that is not possible). The fact that you defined your function reverse_of to return an int indicates that this may be what you originally intended your function to do.
This answer solves the problem by reserving a special return value (in this case 0) of the function reverse_of to indicate that the function failed due to bad input, so that the calling function knows that the input must be repeated. For all other values, the calling function knows that the function reverse_of succeeded. In this case, that solution works, because the value 0 cannot be returned on success, so the calling function can be sure that this value must indicate a failure. Therefore, in your particular case, this is a good solution. However, it is not very flexible, as it relies on the fact that a return value exists that unambiguously indicates a failure (i.e. a value that cannot be returned on success).
A more flexible solution, which keeps a clear area of responsibility among the two functions as stated above, would be for the function reverse_of to not always return a single value, but rather to return up to two values: It will return one value to indicate whether it was successful or not, and if it was successful, it will return a second value, which will be the result (i.e. the reversed value).
However, in C, stricly speaking, functions are only able to return a single value. However, it is possible for the caller to pass the function an additional variable by reference, by passing a pointer to a variable.
In your code, you are declaring your function like this:
int reverse_of(int t,int r)
However, since you are not using the argument r as a function argument, but rather as a normal variable, the declaration is effectively the following:
int reverse_of( int t )
If you change this declaration to
bool reverse_of( int t, int *result )
then the calling function will now receive two pieces of information from the function reverse_of:
The bool return value will indicate whether the function was successful or not.
If the function was successful, then *result will indicate the actual result of the function, i.e. the reversed number.
I believe that this solution is cleaner than trying to pack both pieces of information into one variable.
Note that you must #include <stdbool.h> to be able to use the data type bool.
If you apply this to your code, then your code will look like this:
#include <stdio.h>
#include <stdbool.h>
bool reverse_of( int t, int *result )
{
int n=t;
int r=0;
int count=0;
while (t!=0) /*Loop to check the number of digits*/
{
count++;
t=t/10;
}
if (count==4) /*if it is a 4 digit number then it proceeds*/
{
while (n!=0) /*This loop will reverse the input*/
{
int z=n%10;
r=r*10+z;
n=n/10;
}
*result = r;
return true;
}
else /*This will execute when the input is not a 4 digit number */
{
return false;
}
};
int main()
{
int n, result;
for (;;) //infinite loop
{
//prompt user for input
printf( "Enter a number: " );
//attempt to read number from user
if ( scanf( "%d",&n ) != 1 )
{
printf( "Invalid input!\n" );
//discard remainder of line
while ( getchar() != '\n' )
;
continue;
}
printf( "Your input is: %d\n", n );
//attempt to reverse the digits
if ( reverse_of( n, &result) )
break;
printf( "Reversing digits failed due to wrong number digits!\n" );
}
printf("The reverse of your number is: %d\n", result );
return 0;
};
Although the code is now cleaner in the sense that the area of responsibility of the functions is now clearer, it does have one disadvantage: In your original code, the function reverse_of provided error messages such as:
The number you entered is 5 digit so please enter a four digit number
However, since the function main is now handling all input and output, and it is unaware of the total number of digits that the function reverse_of found, it can only print this less specific error message:
Reversing digits failed due to wrong number digits!
If you really want to provide the same error message in your code, which specifies the number of digits that the user entered, then you could change the behavior of the function reverse_of in such a way that on success, it continues to write the reversed number to the address of result, but on failure, it instead writes the number of digits that the user entered. That way, the function main will be able to specify that number in the error message it generates for the user.
However, this is getting a bit complicated, and I am not sure if it is worth it. Therefore, if you really want main to print the number of digits that the user entered, then you may prefer to not restrict input and output to the function main as I have done in my code, but to keep your code structure as it is.
I'm trying to get the max and min numbers from a contiunous scanf, but I can't seem to work it out. I get time limit exceeded. I need to do it as simple as it gets for a hw as I'm starting to learn C. Any suggestions?
#include <stdio.h>
int main(void) {
int a,b,z,f;
b=1;
while(a > -1){
scanf("%i", &a);
//printf("%i", a);
if((b>a)){
z=a;
}
if((b<a)){
f=a;
}
b=a;
}
printf("Maximum number is: %i\n", f);
printf("Minimum number is: %i", z);
}
You never initialize a before the while loop starts. Set it to 0 when you declare it.
Also, the minimum number will always be the last number you enter to break out of the loop. You probably want to do a check for that right after the scanf.
You're also not doing a proper check against the current min and max. You should be checking a against z and f, not b, and f and z need to be initialized to proper starting values. And while you're at it, change z to min and f to max so they're more descriptive.
If the end of the input is reached, a is not converted and undefined, but itwill very likely retain its old value and the condition may never become false. scanf returns a value: The number of items converted or the special value EOF if the end of input has been reached. Use it.
When you first use a, it is uninitialised and may well be negative. Your algorithm is also not correct. It doesn't find the min and max numbers, it tests how many numbers are greater than the previous number and how many are smaller with a strange result for the first number.
I'll let you work out the min/max logic by yourself, but here's a skeleton for numerical input, which stops at the end of input or at any non-numeric or negative input:
#include <stdio.h>
int main(void)
{
int a;
while (scanf("%i", &a) == 1 && a > -1) {
// process a
}
printf("Max: %i\n", amax);
printf("Min: %i\n", amin);
return 0;
}
Right, i have a 2 files (Distance and time) that have different values on their rows, in the program that divides both values on line into their speed and displays on screen.
This works perfectly, however, the function gives the calculated value to the nearest whole number:
#include <stdio.h>
int main()
{
FILE *fTotDc;
FILE *fTotTc;
int CalScD; //Values for total cycling speed
int CalScT;
float CalScS;
char ScSValue[32];
int DataCount=1; //File line comparison
struct store06 //TICtotD
{
char defTotDc[16];
}stock06[512];
struct store08 //TICtotT
{
char defTotTc[16];
}stock08[512];
fTotDc=fopen("TICtotD.txt","r"); //Opens total distance
fscanf(fTotDc,"%16[^\n]%*.2f", stock06[DataCount].defTotDc);
fTotTc=fopen("TICtotT.txt","r"); //Opens total time
fscanf(fTotTc,"%16[^\n]%*.2f", stock08[DataCount].defTotTc);
printf("|Distance |Time |Speed |");
printf("\n");
printf("|%-16s", stock06[DataCount].defTotDc);
printf("|%-16s", stock08[DataCount].defTotTc);
CalScD = atoi(stock06[DataCount].defTotDc); //Totals are converted to int for calculation
CalScT = atoi(stock08[DataCount].defTotTc);
if(CalScT == 0) //Test for 1/0 error, There is also a failsafe in the edit function which checks for t=0;
{
if(CalScD == 0) //If distance is 0 (As it is by default), the speed is 0.
{
printf("|0 ");
}
else //If distance is not 0 , we have (1/0)*k, which doesn't exist.
{
printf("|Error, Time is 0");//Error message given.
}
}
else
{
CalScS = CalScD/CalScT;
snprintf(ScSValue,32,"%.2f", CalScS); //Turns this int value into a string
printf("|%-16s",ScSValue); //String outputted
}
printf("|"); //last column
getch();
}
This is the code for one line, given that this on a do-while loop until the end of the file.
Input (distance file): Line 1: 4 , (time file) Line 1: 1 .
Expected speed output: 0.25
Actual output: 0.00
Edit: My coding skills are RIP
Edit 2: The mistake, assuming interger/interger would automatically calculate a floating point value. I have changed the code accordingly, it works. Thank you guys.
In CalScS = CalScD/CalScT; first the integer division is executed, then the resulting value is converted to float and assigned to the variable.
Try this
CalScS = CalScD/(double)CalScT;
To first convert the denominator to floating point, then do the division and assign correctly.
Oh ... and (almost) always prefer double to float.
Your calculation line CalScS = CalScD/CalScT; is doing integer division, since both operands are integers.
You need one (or both) of the operands to be floats (or doubles) to get floating-point division.
In your code
int CalScD; //Values for total cycling speed
int CalScT;
both are of type int, and CalScS is of type float.
While calculating the division using
CalScS = CalScD/CalScT;
first, the division will be performed as integer division [resulting in an int value] and after that, the int result will be promoted to float. That's why you're getting the integer output.
change
CalScS = CalScD/CalScT;
to
CalScS = ((float)CalScD )/CalScT;
to enforce the floating point division.
I'm learning C and found this code on a tutorial and it works fine, but if I try to make a decimal number (like 5.5), it prints a negative one in the following arrays and loops itself.
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <math.h>
#include "stdafx.h"
#define ARBEITER 3
#define TAGE 5
#define ARBEITSKALENDER kalender();
int zeitkonto[ARBEITER][TAGE];
/* Fehlerausgabe */
void error(int n) {
printf("%d (?) Falsche Eingabe!!\n", n);
}
ABFRAGE0: {
int i = 0, j = 0;
for (i = 0; i < TAGE; i++) {
printf("\n\t[Eingeloggt als: %s ] Tag %d in der Woche\n", vorname, i + 1);
printf("\t-------------------\n\n");
for (j = 0; j < ARBEITER; j++) {
printf("Arbeiter Nr.%d in Std.: ", j + 1);
scanf("%ld", &zeitkonto[j][i]);
if (zeitkonto[j][i] > 24) {
printf("Ein Tag hat nur 24 Stunden?\n");
PCLEAR WHALLOWELT ABSATZ goto ABFRAGE0;
}
if (zeitkonto[j][i] > 47) {
printf("Wer wünscht sich nicht, man hätte mehr Zeit?");
PCLEAR WHALLOWELT ABSATZ goto ABFRAGE0;
}
}
}
}
What am I doing wrong?
If you want floating point numbers in zeitkonto, replace :
int zeitkonto[ARBEITER][TAGE];
by
double zeitkonto[ARBEITER][TAGE];
and replace
scanf("%ld", &zeitkonto[j][i]);
by
scanf("%f", &zeitkonto[j][i]);
and also replace any
printf("...%ld...", zeitkonto[...][...]) ;
by
printf("...%f...", zeitkonto[...][...]) ;
I'm guessing it's the scanf in the kalender function you have problem with.
If you read scanf you will see that the function returns the number of successfully scanned items. In your case, it will return one, zero or EOF.
If scanf returns one, you successfully read an integer. If it returns EOF the user pressed the end-of-file key combination (or there was another error). The case you really have to look out for is when scanf returns zero, which will happen if you enter something unexpected, like a floating point value. If scanf fails (when it returns zero or EOF) it will not change the value of the variable.
The question have been edited, and I see that I was focusing on the wrong scanf. However, my answer (including the hints on how to solve the problem) is still valid.
If you do want to be able to read floating point numbers, you should of course change the format to "%f" or "%lf", and you must also change the array base type from int to float or double.
zeitkonto is an array of integers - whole numbers. You need fractional numbers, in particular floating point. That means using double and %lf to read them.
I made a program to find if a number belongs to fibonacci series or not and if it does whats its position.Whenever i type a number the if Condition goes wrong.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
int i,x=1,y=1,z,num;
clrscr();
printf("Enter a number to find in fibonacci series:");
scanf("%d",&num);
/*to find if the number is a part of fibonacci series or not*/
if((isdigit(sqrt(5*num*num+4)))||(isdigit(sqrt(5*num*num-4)))) //<-- this if!
{//belongs to fibo!
for(i=1; ;i++)
{
if(x==num)
break;
z=x+y;
x=y;
y=z;
}
printf("%d is the %d term of fibonacci series.",num,i);
}
else
printf("Dear user,The entered number is not a part of the fibonacci series.");
getch();
}
You're misunderstanding the isDigit function.
isDigit takes an ASCII character code and returns true if it represents a decimal digit.
You want to check whether the double returned by sqrt is an integer.
There's an obvious error in your use of isdigit(). That function (usually macro) is used to tell if a character is one of the characters 0..9 - certainly your code is dealing with numbers consistently and there's no need for character checking.
You'll want to take a closer look at what you're trying to accomplish. You're welcome to ask us which C functions might be suitable.
EDIT:
Ah, you want to know if that funky expression is an integer value. Alas, there's no built-in function for that. I haven't tested this, but I'd write
double a = (funky expr);
if (a == rint(a)) ...
... where rint() is a function that returns the double that's the nearest integer value to the given argument.
Why are you using isdigit? The result of sqrt is a double - you need to check that value directly.
You want to check if 5 * num * num + 4 or 5 * num * num - 4 is a perfect square. A function that will do this is:
int is_perfect_sq(double d)
{
double sqroot = rint(sqrt(d));
return (sqroot * sqroot) == d;
}
Note - this is a good disproof of the notion that you should never compare floating point numbers for equality. In this case, it is fine, since a "perfect square" must be an integer.