Accounting for a float in C - c

So I adjusted the code and it seems to work minus one flaw. The shrink is now a float, but not returning the correct answer. when I attempt to shrink 9 for instance it returns 4.0 not 4.5...... 13 returns 6.0? New code is below:
include
int main ()
{
/* variable definition: */
int intValue, menuSelect,Results;
float sResults;
intValue = 1;
// While a positive number
while (intValue > 0)
{
printf ("Enter a positive Integer\n: ");
scanf("%d", &intValue);
if (intValue > 0)
{
printf ("Enter 1 to calculate Square, 2 to Calculate Cube, Enter 3 to Calculate Shrink \n: ");
scanf("%d", &menuSelect);
if (menuSelect == 1)
{
// Call the Square Function
Results = Square(intValue);
printf("Square of %d is %d\n",intValue,Results);
}
else if (menuSelect == 2)
{
// Call the Cube function
Results = Cube(intValue);
printf("Cube of %d is %d\n",intValue,Results);
}
else if (menuSelect == 3)
{
sResults = Shrink(intValue);
printf("shrink of %d is %f\n", intValue,sResults);
}
else
printf("Invalid menu item, only 1 or 2 or 3 is accepted\n");
}
}
return 0;
}
/* function returning the Square of a number */
int Square(int value)
{
return value*value;
}
/* function returning the Cube of a number */
int Cube(int value)
{
return valuevaluevalue;
}
int Shrink(int value)
{
return value*1/2;
}

Results = Shrink(intValue);
printf("shrink of %d is %f\n", intValue,sResults);
You're storing the result in Results, but then printing sResults. Those are two different variables, and sResults is still zero because it hasn't been assigned a value. Change sResults to Results in your printf statement.
However, since you're doing integer division, you'll get a result that's truncated to an integer: Shrink(5) will return 2. To fix that, you'll need to change Shrink to take a float argument instead of int, return float instead of int, and assign its result to sResult instead of Result.
Also, you're probably getting compiler warnings about the Square, Cube, and Shrink functions being undeclared. Those happen because the code that calls the functions is before the code that says what they are. It hasn't caused an actual problem for you yet, because the compiler handles the situation by assuming that each function takes an int argument and returns an int result, which coincidentally happens to be true. But if you change any of the functions to operate on float instead of int, your program will break because the calls will still be compiled as if they were int.
Move the three math functions up above main, or leave them at the bottom and put these lines before main:
int Square(int value);
int Cube(int value);
int Shrink(int value);
Those are called declarations, and they tell the compiler what types the functions operate on, so it knows how to handle them even before it sees their implementation. If you change the functions to operate on float instead of int, change the declarations to match.

Related

i can only call a function once to compare 2 numbers using pointers

i have to compare 2 numbers using pointers but i can only call my function one time to get the number then i have to find the largest number from the 2. then I have to display which one was largest.I am having a hard time beacause I dont know where I went Wrong because the second number it always says is larger when I enter the larger one first. Can someone help? Here is what I tried.
#include <stdio.h>
void getnumbers(float*,float*);
float findlargest(float*,float*);
void displaylargest(float);
int main ()
{
float num;
float num2;
float largest;
getnumbers(&num,&num2);
largest=findlargest(&num,&num2);
displaylargest(largest);
return 0;
}
void getnumbers(float*num,float*num2)
{
printf("Enter a number\n");
scanf("%f",num);
printf("Enter a number\n");
scanf("%f",num2);
}
float findlargest(float*numptr,float*num2ptr)
{
if (*numptr>*num2ptr) {
return *numptr;
}
else {
return *num2ptr;
}
}
void displaylargest(float largest)
{
printf("\nthe largest is %f ",largest);
}
Lets start with getNumbers():
To get a function to return more than one value, you can pass parameters by reference. This post has a good explanation of passing parameters by reference.
When we pass-by-value we are passing a copy of the variable to a function. When we pass-by-reference we are passing an alias of the variable to a function.
Where the alias is a pointer to the memory location of num or num2 declared in main() (see function below). This allows you to change their value inside the function the variables were passed to.
void getnumbers(float *num, float *num2)//pass by ref to get two numbers
{
printf("Enter a number\n");
scanf("%f",num);//"%2f" is not something you would do
printf("Enter a number\n");
scanf("%f",num2);//assign to num2, not num
}
Now findLargest() really does not need to be taking pointers as parameters, but it can if the assignment requires. You would only do that if you intend to change their value. If you need to only use the value, you just pass by value:
//much more concise and does the exact same thing!
//Normally wouldn't use pointers here, but it is a requirement for the assignment
float findlargest(float *num, float *num2)
{
return *num > *num2 ? *num : *num2;
}
Now your main becomes:
int main ()
{
float num = 0;//always a good idea to initialize variables!
float num2 = 0;
float largest = 0;
getnumbers(&num, &num2);//pass by reference
largest = findlargest(&num, &num2);//pass by value
displaylargest(largest);
return 0;
}
i believe it is because you are using the same variable to enter a number
i.e. num 2 doesn't have a value
void getNumbers(float *num1, float *num2){
printf("Enter a number\n");
scanf("%2f", num1);
printf("Enter a number\n");
scanf("%2f", num2);
}
this passes the num1 and num2 variable by "call by reference" and allows you to directly modify the value stored in the pointer num1 and num2, so you don't have to return any value too.
then when you compare it should compare two values you enter in now.
You are never assigning num2 in main. Your getnumbers function asks the user for two numbers and only returns one of them. I don't know why you have to use pointers for your getlargest function -- that makes no sense -- but if those are your requirements, then okay.
To fix your problems, rewrite getnumbers to take in two pointers to float where you will then pass to scanf.
Your main () function inside the num2 is not assigned, because the initial num2 is 0, so you get the result is always num2 the smallest。
Your getnumbers () also has an error, it can only return the last keyboard input value。
bie jiao yin yu.
your function "getnumbers" only return one value,num2 Uninitialized.
There are 2 solution:
(1)add
num2 = getnumbers();
and delete
printf("Enter a number\n");
scanf("%2f",&num);
(2)modify your function
getnumbers(&num, &num2);
void getnumbers(float *num1,float *num2) {
printf("Enter a number\n");
scanf("%f",num1);
printf("Enter a number\n");
scanf("%f",num2);
}

Variable Buffer?

I have this code which calculates the exponential power of a value, both of which is entered by the user, example, user enters 2^3 = 8, its suppose to work like this but somethings wrong, the end result is 608, when I debug in the pwra function in the counter, even before the counter initiates the result value is set, from where I dont know because I did not set it so the end result is 608. I feel like its a buffer issue but I have tried fflush both in and out, it doesnt work. So when I copy this code to a new window, it works for sometime, then same again, earlier it was showing 624 as the end result.
#include <stdio.h>
int pwra (int, int);
int main()
{
int number, power, xx;
printf("Enter Number: ");
scanf("%i", &number);
printf("Enter Number: ");
scanf("%i", &power);
xx=pwra (number,power);
printf("Result: %i", xx);
return 0;
}
int pwra (int num, int pwr)
{
int count, result;
for(count=1;count<=pwr;count++)
{
result = result*num;
}
return result;
}
Another thing, how can I calculate the exponential value from a float, because when I change all the int to float the end result is always 0.00000 even with %lf.
You're hitting undefined behavior for the below line
result = result*num;
as you've not initialized result. The initial value for an uninitialized automatic local variable is indeterminate. Using that invokes UB.
Always initialize your local variables, like
int count = 0 , result = 0 ; //0 is for illustration, use any value, but do use
Then coming to the case, where you want to change all ints to float, only changing the data type of the variable is not sufficient. You need to change the corresponding format specifiers, too.

Math giving incorrect results with value obtained from scanf()

I'm trying to write a function that can, given one, convert between to all four of Kilometers, Miles, Nautical Miles, and Furlongs given one of the four. My Main function looks like:
int main() {
Scale scale; // declared in the header file "length.h"
double value, kilometers, miles, nautical_miles, furlongs;
// prompt user for unit to convert from
printf("\nPlease select which unit you want to convert from:\n");
printf("1. Kilometers\n2. Miles\n3. Nautical Miles\n4. Furlongs\n");
scanf("%d", &scale);
// Get value user wants
printf("Enter value for unit you selected: ");
scanf("%d", &value);
int err = convertLength(&kilometers, &miles, &nautical_miles, &furlongs, scale);
printf("value given was %d\n", value);
kilometers *= value;
//kilometers *= 2;
//kilometers = kilometers * value;
printf("%g Kilos\n%g miles\n%g naut mi\n%g fur", kilometers, miles, nautical_miles, furlongs);
return 0;
}
The conversion is taking place in the file "length.c" and I have only been debugging the kilometers case so far. The Enum declaration for scale is in a header file "length.h".
The issue is that when I multiply kilometers in main() by value, I get an incorrect result (such as 4.940e-324). However, when I only multiply by a constant, like the commented out line //kilometers *= 2; I will get the correct answer (2 in that case). What's going wrong with the variable value that's making it behave in this way?
int convertLength(double *kilometers, double *miles, double *nautical_miles, double *furlongs, Scale scale) {
switch(scale) {
case KILOMETERS:
printf("Kilometers was chosen\n");
*kilometers = 1;
*miles = 1/1.609347219;
*nautical_miles = *miles * 1.15078;
*furlongs = *miles / 8;
break;
Change scanf()'s specifier, for double it is "%lf", not "%d", also
Turn on compiler warnings to avoid this kind of mistake, it should warn you about the incompatibility between the passed pointer and the expected pointer.
Check scanf()'s return value to ensure that your data is find instead of just assuming that it is.

I can't get this (simple) loop to work properly

I'm in a programming class right now, and was asked to create a program that calculated the sum of a user's input for multiple numbers--then calculate the nth root of the sum. If the number they input was less than 0, the loop is supposed to discard the less than 0 number, then ask again.
Unfortunately, no matter what number I input--it displays "Value needs to be greater than zero!" I tried putting a fflush(stdin); statement in the loop, but that didn't seem to do anything.
Here is my code. I really appreciate any and all help.
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
int mTotalNums, mNth; //amount of numbers in set
float mProd = 1, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
mNth = mTotalNums; //set the value of mTotalNums equal to mNth becuase we'll lose the original value of mTotalNums after the loop
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
}
mNroot = pow(mProd, (1 / mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
"%lf" is the scanf format for a double, but x is declared as float.
To scan a float, you have to use the %f format.
Note also that mTotalNums is not decremented in the loop, so that it will never
terminate.
Read the documentation of scanf(3). Since x is declared as a float, use %f as the scanf format control string. Also, take into account the result of scanf (it would be 1 if successfully read one item).
You should enable all warnings and debug info in your compiler, then learn how to use the debugger (notably to run your program step by step, display local variables, etc....).
(On Linux, if compiling with gcc -Wall -g you would get a useful warning, and the gdb debugger would be helpful...)
Try these modifications to your program (added comments with changes made)
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
//amount of numbers in set
int mTotalNums, mNth;
// Change to double for added precision
double mProd = 1.0, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
// Set the value of mTotalNums equal to mNth becuase
// we'll lose the original value of mTotalNums after the loop
mNth = mTotalNums;
// Don't forget to decrement the loop counter
while (mTotalNums-- > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else {
printf("\nValue needs to be greater than zero!\n");
}
}
// Change to 1.0 to force compiler to treat as a double
mNroot = pow(mProd, (1.0 / mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
You mention "calculate the nth root of the sum", but your loop is clearly tallying the cumulative product. To change it to calculate the sum, try the following additions:
// Declare a sum variable
double sum = 0;
// Sum inside your while loop
sum += x;
// Calculate the nth root of the sum instead
mNroot = pow(sum, (1.0 / mNth));
Add printf commands to see what your variables contain before you check them in your logic statements.
You also need to do something to increment/decrement your variable for your while loop... currently nothing is changing mTotalNums, so it will be an infinite loop.
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
printf("x=%d", x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
mTotalNums--;
}

Determining if a float has a fractional part?

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.

Resources