Im writing a C program that is supposed to add every number until it hits a sentinel value. Then average it all together.
Im not sure where the problem is but I think it might be that num never actually changes. Any help is appreciated.
#include <stdio.h>
int sentinal = 9999;
int iterations = 0;
int total = 0;
int average;
int num;
int main(void){
do{
printf("Enter a number to add:\n");
scanf("%d\n", num);
total = total + num;
iterations++;
}while (num != sentinal);
average = total/iterations;
printf("%d\n", average;
return 0;
}
Running version
#include <stdio.h>
int main(){
int sentinel = 9999;
int iterations = 0;
int total = 0;
float average;
int num;
while(1){
printf("\nEnter a number to add: ");
scanf("%d", &num);
if (num == sentinel){
break;
}else{
total = total + num;
iterations++;}
}
average = (float) total/iterations;
printf("%f\n", average;
return 0;
}
Your problem is in the line:
scanf("%d\n", num);
scanf requires a memory address of the variable where should put the value the was read. This is done using the operator &. Your code should be:
scanf("%d\n", &num);
scanf() takes a pointer to the value parsed from standard input. You're passing the actual value, not the pointer to the value.
There are many tools in Linux to find out Segmentation and other compilers as well. If you want to really debug where your code is popping segmentation fault , you can use GDB and valgrind .It exactly gives you where you have error in your code .
Provide address i.e. & when storing value using scanf.
Declare average as float, and while calculating average use average = (float) total / iterations and use %f while printing average.
Check your printf when you are printing average, closing bracket is missing.
Related
Program takes an integer input num from the keyboard and computes the sum of square of i for all I from 1 to num (inclusive).
#include <iostream>
#include <math.h>
int main()
{
int num;
int total;
printf("Please enter a number:");
scanf("%d", &num);
for (double i = 1; i <= num; i++) {
total += (i*i);
printf("%d", total);
}
}
The code above compiles correctly, but when inputting 5 it prints 15143055. Why is it doing this?
#include <iostream> is c++. #include <math> is not used. total is uninitialized. Comparing floating point values may not behave the way you want, so using a (unsigned) integer type instead as a loop counter. Loop values by convention start at 0 instead of 1 in c (you could increment i fist thing in the loop to avoid the double (i+1) but this will be optimized out anyways). Also, your loop not run for a negative value so just require unsigned values. As you sum integers the result ought to be an integer, but double would give you a larger range so I left it as such. Missing return:
#include <stdio.h>
int main() {
unsigned num;
printf("Please enter a number: ");
scanf("%u", &num);
double total = 0.0;
for (unsigned i = 0; i < num; i++) {
total += (i+1)*(i+1);
}
printf("%lf\n", total);
return 0;
}
and the resulting output:
Please enter a number: 3
14.000000
I'm coding in c and have been attempting to make an average calculator, as i am new to coding and only just starting and my code won't work after i input a number for it. the way it should work is you input a number, the code keeps track of the overall number and the amount of numbers entered and prints out the average, doing this all in "do while" loop
my code:
int main()
{
float overall = 0;
float entered = 0;
float times = 0;
float avg = 0;
printf("AVERAGE CALULATOR\n\npress 0 when complete\n\n");
do{
printf("current average: %.2f\n\n", avg);
printf("input number: ");
scanf("%f", entered);
overall += entered;
times++;
avg = overall / times;
}while(entered != 0);
return 0;
}
pleae inform me of incorrect code if you find it
You just forgot the (&) in scanf after the comma.
scanf("%f", &entered);
Scanf needs a pointer to your adress.
#include <stdio.h>
#include <conio.h>
int getn(int n, int i);
int main()
{
int n, i;
getn(n, i);
getch();
return 0;
}
int getn(int n, int i)
{
int even = 0;
int odd = 1;
int avg;
printf("Enter ten integers: \n");
for (i = 1 ; i <= 10 ; i++)
{
printf("Integer %d: ", i);
scanf("%d", &n);
if ( n % 2 == 0 )
{
even = even + n;
}
else
{
odd = odd * n;
}
}
avg = even / 10;
printf("\n\nAverage of even numbers: %d", avg);
printf("\nProduct of odd numbers: %d", odd);
}
It seems the even calculations worked but when it comes to odd it gives the wrong answer. Please help
Our instructor wants us to use looping or iterations. No arrays. Please help me
First, your C code needs some correction:
at least give the prototype of getn before using it
getn is defined to return an int and doesn't return anything. Either replace int with void or return a value.
Second,
Your code computes the product of ten numbers, if this product is too big, it cannot be store as-is in an int. For example, it works well if you enter ten times number 3, the result is 59049, but if you enter ten times number 23, it will answer 1551643729 which is wrong because 23^10=41426511213649 but that can't be stored in an int. This is known as arithmetic overflow.
Your average is bad, because you sum ints, but the average is (in general) a rational number (average(2,3)=2.5 isn't it ?). So double avg = out/10.0; (means compute a floating division) and printf("Average %f\n",avg); would be better.
I tried to search this everywhere, but it's kind of difficult to word, it's most likely a simple fix. Basically when I go through my program that is supposed to compute the average rainfall for a year, it comes out with a very large number, however, I thought it may have been just that I was doing the arithmetic wrong or had a syntax error of some sort, but that was not the case, when I checked the value that the function returned it was the proper value.
#include <stdio.h>
#include <string.h>
void getData(float *, float *);
int main()
{
char state[2], city[81];
float rainFall[12], outputAverage, *pAverage;
printf("Name Here\n");
printf("Please enter the state using a two letter abreviation: ");
gets(state);
printf("Please enter the city : ");
gets(city);
pAverage = &outputAverage;
(getData(rainFall, pAverage));
printf("%.2f", outputAverage);
return (0);
}
void getData(float *rainFall, float *pAverage)
{
int i;
float total;
for (i=0; i<12; i++)
{
printf("Please enter the total rainfall in inches for month %d: ", i+1);
scanf("%f", &rainFall[i]);
total += rainFall[i];
}
*pAverage = total / 12;
}
you need to initialize total
float total = 0.0;
Initialize the total to 0
Why you make it complicated? Why not just
return total / 12 ?
and called it like
outputAverage = getData(rainfall)
This is a classic problem in C programming. You are mixing strings and numbers on the input. You are better off reading the input into a string and then, using sscanf to parse it properly.
You have uninitialized variable total which is taking garbage value, thus you see a very large answer.
changed your main.. have a look and let me know if you have understood what changes i have made?
#include <stdio.h>
#include <string.h>
void getData(float *);
int main(int argc, char*argv[])
{
char state[3]={0}, city[81]={0};
float outputAverage;
printf("Name Here\nPlease enter the state using a two letter abreviation: ");
scanf("%s",state);
printf("Please enter the city : ");
scanf("%s",city);
getData(&outputAverage);
printf("The Average Rainfall recorded for the year is %.2f\n", outputAverage);
return 0;
}
void getData(float *pAverage)
{
int i;
float rainFall[12]={0}, total=0;
for (i=0; i<12; i++)
{
printf("Please enter the total rainfall in inches for month %d: ", i+1);
scanf("%f", &rainFall[i]);
total += rainFall[i];
}
*pAverage = total / 12;
}
However instead of using gets you should use fgets but i forgot how to counter the issue of using simultaneous fgets to read input from the standard input stream.
Also initialize the total variable as you are adding in the loop new values to existing value in that variable which would not necessarily add to zero as the premier element. so it could be any garbage value + loop values.
I understand you are practicing pointer concept so you passed the address of the array of floats to your second function but if the rainfall function is not useful in main, Better to restrict the same where it would be useful
i'm learning C.
i'm using ubuntu and have Code::Blocks as IDE
i have this code:
#include <stdio.h>
int rev (int num);
int main (){
int numb = 0;
printf("%d\n\n", numb);
printf("Please enter a number. Enter 9999 to stop\n");
scanf("%d", &numb);
printf("there?");
printf("%d\n", numb);
while (numb != 9999){
printf("The reversed number is %d\n", rev(numb));
printf("Please enter a number. Enter 9999 to stop\n");
scanf("%d", &numb);
} /* end of while */
}
int rev (int num){
printf("here?");
int total = 0;
long max = 10;
long max_const = 10;
printf("here");
for (max; max < num; max *= 10);
printf("%ld", max);
max_const = max;
for (int i = 0; i <= max_const; i *= 10, max /= 10){
total += num / max * i;
} /* end for */
return total;
}
I'm doing it in this way cause my book isn't clear...however, the problem is that it raise a Floating Point exception, in scanf...i'm typing normal numbers... the strange thing is that if i type everything but 9999, the program crash. if i type 9999, it prints 'there?' (so scanf it's ok) and stop later, obviously. why?
Thank you.
The two existing (be sure to return the result in rev, and put \n on the ends of printfs to be sure they make it through the buffer) answers are good points, but not the thing that's actually triggering your floating point exception. Try running it in a debugger, and you'll see that your algorithm is bad: eventually max becomes zero and you divide by it. I'll leave fixing that as an exercise for the reader; the problem isn't anything to do with scanf.
Your rev function needs to return the reversed number.