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--;
}
Related
I'm having a problem with getting my code to pick up the user input of the variables number and result. The correct way the code should act is: When user puts in a positive value, code should square root this value and display the new value. As of now, there are no error messages, the code runs fine, just not the way i want it to.
It does NOT pick up any value and does not square root math either, when looking at the output.
I also need to use pointers when doing this code (weird imo). Pointers are something im very new to so i expect to get quite the critique on that department.
I have tried reading several tutorials on pointers and the understanding of sqrt but it feels like key parts of those things still confuse me.
Code: (Consists of a function squareRoot that does the math and main that handles input/output)
#include <stdio.h>
#include <math.h> //needed for sqrt()
#define POSITIVE 1 //not used atm
#define NEGATIVE 0 //not used atm
float squareRoot(float number, float * result) {
return * result = sqrt(number); //calculate the square root of a number
}
int main() {
float number = 0;
float * result = malloc(sizeof(float));
printf("Enter a float value: ");
scanf("%f", &number);
squareRoot(number, result);
if (number < 0) {
printf("Square root of a negative value is not possible.");
}
if (number > 0) {
printf("Square root if %.2f is: %.2f "), number, result;
}
return 0;
}
Any help or constructive criticism is greatly appreciated!
result is a pointer, you need to dereference it.
printf("Square root if %.2f is: %.2f ", number, *result);
If you didn't get a compiler warning for the type mismatch, increase your warning level.
Edit:I solved the issue by first multiplying the float value by 100, then rounding it with roundf() function, then casting it to an integer to be stored in an integer variable. I did the remaining operations with integer values from there on and everything worked. Even though the solution offered by #JacobBoertjes actually worked, my assignment requiered me to use get_float() from the cs50.h library, so I didn't implement it. Here's the final code:
// Get user input as a positive float value
float f_change;
do {
printf("Change owed: ");
f_change = get_float();
} while(f_change < 0);
// Round & cast
int int_change = (int) roundf(f_change * 100);
My program accepts an amount of money, say $4.20, and figures out the least amount of coins with which it can represent this value. For example, desired output from the program with $4.20 as an input would be: 16 quarters ($4.00), 2 dimes ($0.20).My program successfully calculates the number of quarters, but fails to do so while working on dimes. The cause of this failure is the second for loop in the code. 0.10 >= 0.10 does not evaluate to true, so the last iteration of the loop never happens. What am I doing wrong? Here is the code. I provided test print statements with their outputs written as comments.
#include <stdio.h>
#include <cs50.h>
int main(void) {
// Fake user input
float owed_coin = 4.2f;
// Initialize coin variables
int coin_count = 0;
float quarters = 0.25f,
dimes = 0.10f;
// Calculate quarters
while(owed_coin >= quarters) {
owed_coin -= quarters;
coin_count += 1;
}
printf("owed_coin: %.2f\ncoin_count: %d\n\n", owed_coin, coin_count);
// Prints owed_coin: 0.20
// coin_count: 16
// Calculate dimes
while(owed_coin >= dimes) {
owed_coin -= dimes;
coin_count += 1;
}
printf("owed_coin: %.2f\ncoin_count: %d\n\n", owed_coin, coin_count);
// Prints owed_coin: 0.10
// coin_count: 17
}
Floating point comparison is generally a bad idea because floats often become non-exact and thus will not be exactly equal. As #bruceg mentioned, a good solution is to keep your monetary values in terms of cents, so that you avoid using a float.
You could replace float owed_coin = 4.2f; with int owed_coin = 420;
In terms of gathering user input into this number, here is my suggestion using scanf
int n1, n2;
printf("Please enter amount:");
scanf("%d.%2d", &n1, &n2);
owed_coin = n1*100 + n2;
Another solution allows you you keep your variables as floats, and just compare for a very small difference between the two. It can be found here: What's wrong with using == to compare floats in Java?
It uses the Java Math library, but a similar solution could look something like this in C:
while((owed_coin - dimes) >= -0.001) {
owed_coin -= dimes;
coin_count += 1;
}
If you want to learn more about why floating point numbers suffer small innacuracies then check this out: https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems
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;
}
I ran it, and everything seems to be fine--except that it keeps giving me a margin of error of 1. Why is it doing this?
The program is supposed to prompt the user to input an estimation for the cube root of 3, and it uses Newton's method of approximation to show how many attempts it took to get to the approximation. After 500 attempts or a margin of error less than 0.000001, it's supposed to exit the loop. Why, though, doesn't the margin of error change?
Here's my code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
float a, i, e; //declare float variables
printf("Consider the function f(x) = x^3 - 3 = 0.\n");
printf("Simplifying, we get x^3 = 3.\n");
printf("Simplifying it further, we get x = 3^(1/3).\n");
printf("Enter your estimate of the root: ");
scanf("%f", &a); //prompt user to guestimate
printf("So you're saying that x = %f.\n", a);
i=0; //initiate attempt counter
e=abs((a-pow(3, (1/3)))/pow(3, (1/3))); //margin of error formula
while (e>=0.000001 && i<=500) //initiate while loop with above expressions
{
if (a!=pow(3, (1/3)))
{
printf("Attempt %f: ", i);
a = a - (pow(a, 3) - 3)/(3*pow(a, 2));
printf("%f, ", a);
printf("%f margin of error\n", e);
i=i+1;
}
else
break;
}
}
abs() deals with ints and will return an int, you need fabsf().
In the same way, pow() is for doubles, you should use powf().
Another mistake is writing 1/3 and expecting 0.333... as a result. 1 and 3 are int literals, so the operation performed is integer division. You need to use float literals, such as 1.0f/3.0f.
That's it for type compatibility. I can see another error however : you expect e to somehow remember its formula and reapply it automagically. That's not how imperative languages work : when you write e = something, "something" is calculated and stored in eĀ once and for all. You're doing it correctly for a, now just bring e=abs(...); inside the while loop to update it each time.
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.