In Java,I need to ask user input for two integers. The program needs to divide by these two integers and produce a decimal to the sixth place.
I know that i will need to name two integers: numerator and denominator. Also, I need to name a double variable: result.
Thanks for the help!!
You haven't given any clues as to the language or platform you are using, but here is a basic example written in C running on a console.
#include <stdio.h>
int main()
{
int num, den;
double quo;
printf("Enter numerator: ");
scanf("%d", &num);
printf("Enter denominator: ");
scanf("%d", &den);
if (den == 0)
printf("Divide by zero\n");
else {
quo = (double)num / (double) den;
printf("Quotient = %.6f\n", quo);
}
return 0;
}
Related
I am learning to program in C and C++.
My C program keeps crashing after input, here's the code:
\#include\<stdio.h\>
main(){
int n, i,a,sum=0;
printf("How many numbers?\\n");
scanf("%d", &n);
for(i=0;i\<n;i++){
printf("What's the %d number\\n", i+1);
scanf("%d", &a);
sum=sum+a;
}
printf("Sum is %d", sum);
}
And here's the output from my compile log
Compiler: Default compiler
Executing gcc.exe...
gcc.exe "C:\\Dev-Cpp\\Reee.c" -o "C:\\Dev-Cpp\\Reee.exe" -I"C:\\Dev-Cpp\\include" -L"C:\\Dev-Cpp\\lib"
Execution terminated
Compilation successful
There is 0 errors and 0 warnings.
If someone knows how to fix it I would be really thankful.
I tried to make a program that sums up all the numbers in a row. I expected a sum output but the program crashed after input. The program crashes after I input the last number in a row, where it should sum up all of them and output the sum.
I copied this program, added "void" to the main function
and changed the include statement like this ⬇️
everything worked just fine
#include <stdio.h>
void main()
{
int n, i, a, sum = 0;
printf("How many numbers?\\n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
printf("What's the %d number\\n", i + 1);
scanf("%d", &a);
sum = sum + a;
}
printf("Sum is %d", sum);
}
//output:
How many numbers?\n2
What's the 1 number\n4
What's the 2 number\n5
Sum is 9
you should use only one \ when you print somthing.
#include <stdio.h>
#include <cs50.h>
int GetPositiveInt();
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower?");
scanf ("%d", &min);
int numbtl = min * 12; /*computes number of bottles*/
if (min > 0)
{
printf ("Taking a shower you use %d bottles of water", numbtl);
}
else
{
printf ("Please enter the positive number: \n");
scanf ("%d", &min);}
return min;
}
}
I've written this program but I've got some bug in else place.
Here is the text which I get trying to execute this program.
~/workspace/pset1/ $ make water
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow water.c -lcs50 -lm -o water
~/workspace/pset1/ $ ./water
How many minutes does it take you to use a shower?0
Please enter the positive number:
10
~/workspace/pset1/ $
Let me explin what I mean by this code and its execution. This code is used to compute how many bottles of water you use while taking a shower. 1 minute of shower equals 12 bottles.
If you enter the positive integer (for example, 10) the result will be like this:Taking a shower you use 120 bottles of water. BUT if you enter 0 or negative integer the program will ask you to enter the positive integer. And here is when the problem occurs. After entering the positive integer I get the result of 0 bottles.
Lets break down your program and see what it is doing; first
int GetPositiveInt();
Is a forward declaration for a function that is never used or defined, you can remove it entirely.
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower?");
scanf ("%d", &min);
Here we define the main function (the entry point to a c program) and declare a variable of type int called min. Then print out a line asking for user input and read in their response storing it in the min variable.
int numbtl = min * 12; /*computes number of bottles*/
Here you process min by multiplying it by 12 and storing the result in numbtl.
if (min > 0)
{
printf ("Taking a shower you use %d bottles of water", numbtl);
}
Here you check if min is valid, if it is you print the response. Here you can see the success path of your program is correct, the problem is what happens when min is not greater than 0. (Note there was a minor formatting error in this next bit that I corrected by what I assume you meant - note that this is why correct indenting and formatting is important).
else
{
printf ("Please enter the positive number: \n");
scanf ("%d", &min);
}
If min is not valid (ie less than or equal to 0) then you ask for another input and store it in min.
return min;
}
Lastly you return whatever is stored in min. Note you never actually do anything with this second value, except return it.
Side note: The return value on main is used as the exit status of your application. You can see the exit status of the last command in bash with echo $?.
$ ./water
How many minutes does it take you to use a shower?
2
Taking a shower you use 24 bottles of water
$ echo $?
2
This is probably not what you want. The exit status is normally 0 to indicate success and a positive number otherwise. This last return you will likely want return 0 to indicate your program has run successfully.
Now for the logic of your program, what it looks like you are trying to do is obtain some input from the user; validate it (obtaining new input if its invalid); then process it. So the first thing to do is move your processing to the end of your program
int main (void)
{
int min; /*variable to hold minutes*/
...
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}
Now we just need to acquire and validate the user input; a typical algorithm to do this is:
prompt for user input
while (input is not valid) {
reprompt for user input
}
process user input
Converting this to c your applications ends up with;
int main (void)
{
int min; /*variable to hold minutes*/
printf ("How many minutes does it take you to use a shower? ");
scanf ("%d", &min);
while (min <= 0)
{
printf ("Please enter the positive number: ");
scanf ("%d", &min);
}
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}
This will continue to ask the user for a positive number until they either enter one or hit crtl+c to kill the command. Once a valid number has been obtained it will processes it and print out the result.
#include <stdio.h>
#include <string.h>
int main (void)
{
long min;
char msg[255];
strcpy(msg,"How many minutes does it take you to use a shower?\n");
do {
printf ("%s", msg);
scanf ("%lu", &min);
strcpy(msg , "Please enter the positive number: \n");
}while( min <= 0 );
long numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %lu bottles of water", numbtl);
return 0;
}
You can also use a goto label. Here I used a goto label named start. If a number less than zero is entered then the program goes to beginning of the program. Hope, It helps.
#include<stdio.h>
int main (void)
{
int min; /*variable to hold minutes*/
start :
printf ("How many minutes does it take you to use a shower?\nEnter here : ");
scanf ("%d", &min);
if (min <= 0)
{
printf("Enter a number grater than zero\n\n");
goto start;
}
int numbtl = min * 12; /*computes number of bottles*/
printf ("Taking a shower you use %d bottles of water", numbtl);
return 0;
}
Consider the following:
#include <stdio.h>
int main()
{
int first=9;
int second=0;
double ratio;
if(second==0)
ratio="n/a";
else
ratio=(double)singularCount/pluralCount;
printf("ratio is: %f", ratio);
return 0;
}
This obviously wont run as it should.
How can I modify my code/print statement to print a float if there are no problems, and n/a if there is division by 0?
I will be printing many of these ratios in a list, so I'd like to see "n/a" when there is division by 0.
Desired Output:
ratio is: n/a
You are doing something wrong...
you shouldn't put a string into a double variable.
What you want to do is to use isnan on undefined doubles (which are completely legit to hold),
and have an if statement on it.
something like:
if (isinf(ration)) printf("ration is undefined\n");
else printf...
This way you can send the double and get it from methods/procedures/functions (that I urge you to use for code separation) and yet you'll be able to get different behaviors.
by the way - look at this code:
#include <stdio.h>
#include <math.h>
void main()
{
double d = 1.0/0.0;
if (isnan(d)) printf("it is n/a\n");
else if (isinf(d)) printf("it is inf\n");
else printf("%f\n",d);
}
another thing - %f in the case of inf or nan will just print the strings "inf" and "nan", if it's good enough for you - you don't need to change a thing, if it is for your eyes.
if (second == 0) {
printf("ratio is: n/a");
} else {
printf("ratio is: %f", (double)singularCount/pluralCount);
}
I have removed scanf from the code and the rest of the program runs with no issue. When the code reaches scanf, and after I type a number, xcode 'loses connection' and displays the error "Program ended with exit code: -1". I have also tried making 'input' an int, changed the name of variable input in case there was a conflict there, and tried it without fflush in the code. I am running Mountain Lion on Oracle VM Virtualbox, and my computer is on Windows 7, if that's relevant.
What am I doing wrong?
#import Foundation/Foundation.h
#include stdio.h
int main(int argc, const char * argv[])
{
#autoreleasepool {
float input = 1;
int i = 0;
float total = 0;
int max = 0;
int min = 1000;
while (input != 0){
NSLog(#"Please put in a number. \n");
scanf("%f", &input);
fflush(stdin);
if(input > max){
max = input;
}
if(input < min){
min = input;
}
total = total + input;
i++;
}
printf("The number of entered numbers was %i \n", i);
printf("The sum of the entered numbers is %f\n", total);
total = total/i;
printf("The average of all the numbers is %f\n", total);
printf("The highest number entered is %i\n", max);
printf("The lowest number entered is %i\n", min);
}
return 0;
}
fflush(stdin);
You probably want
fflush(stdout)
I'm not sure what fflush() will do with an FILE* opened for input.
This may or may not be the cause of your issues.
Return and Enter key have a different meaning inside Xcode. You go to the product menu and select build build for running and execute it in the terminal it will work fine.
Inside Xcode the Enter key in the numpad stops the program with a -1 return code. I am not sure whether this is bug or a feature, but I could not find the key in the keybinding for Xcode.
Please check here
I have to Create a dynamic array capable of holding 2*n Fractions.
If the dynamic array cannot be allocated, prints a message and calls exit(1).
It next fills the array with reduced random Fractions whose numerator
is between 1 and 20, inclusive; and whose initial denominator
is between 2 and 20, inclusive.
I ready did the function that is going to create the fraction and reduced it. this is what I got. When I compiled and run this program it crashes I cant find out why. If I put 1 instead of 10 in the test.c It doesn't crash but it gives me a crazy fraction. If I put 7,8,or 11 in the test.c it will crash. I would appreciate if someone can help me.
FractionSumTester.c
Fraction randomFraction(int minNum, int minDenom, int max)
{
Fraction l;
Fraction m;
Fraction f;
l.numerator = randomInt(minNum, max);
l.denominator = randomInt(minDenom, max);
m = reduceFraction(l);
while (m.denominator <= 1)
{
l.numerator = randomInt(minNum, max);
l.denominator = randomInt(minDenom, max);
m = reduceFraction(l);
}
return m;
}
Fraction *createFractionArray(int n)
{
Fraction *p;
int i;
p = malloc(n * sizeof(Fraction));
if (p == NULL)
{
printf("error");
exit(1);
}
for(i=0; i < 2*n ; i++)
{
p[i] = randomFraction(1,2,20);
printf("%d/%d\n", p[i].numerator, p[i].denominator);
}
return p;
}
this is the what I am using to test this two functions.
test.c
#include "Fraction.h"
#include "FractionSumTester.h"
#include <stdio.h>
int main()
{
createFractionArray(10);
return 0;
}
In your createFractionArray() function, you malloc() space for n items. Then, in the for loop, you write 2*n items into that space... which overruns your buffer and causes the crash.