Why didn't this code work after adding "res=pow(arr[i],x)"
I want it to print like this
"printf("%d * %d = %d \n",i+1,x,pow(arr[i],x));"
The code doesn't work untill i print like this
"printf("%d * %d = %d \n",i+1,x,res)));"
#include<stdio.h>
#include<math.h>
int main()
{
int arr[5];
for(int i=0 ; i<5 ; i++){
printf("enter the numbers %d\n",i+1);
scanf("%d",&arr[i]);
}
int x;
printf("what is power would you like...\n");
scanf(" %d",&x);
printf("The power of the array elements is...\n");
for(int i=0 ; i<5 ; i++){
printf("%d * %d = %d \n",i+1,x,pow(arr[i],x));
}
return 0; // 1*2=1*1 , 3*2=3*3
}
pow returns a double. You need %lf format for the third argument or you'll get undefined behaviour trying to format a floating point value with an integer %d format (most compilers issue a warning about this BTW).
quickfix
printf("%d * %d = %lf \n",i+1,x,pow(arr[i],x));
Assigning the result to an integer workarounds the issue. That's why it works then (but sometimes it leads to rounding errors so beware!)
You may have a look at integer power algorithms instead. pow is more suited for floating point operations.
Related
For some reason my code will consistently print out zeros.
I was supposed to make a code in which I enter three numbers,
The first number
The ratio
The amount of numbers to be displayed
The code should display those numbers.
Here is the code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void forloop(int firstNum,int ratio,int repeats);
int main(void)
{
int firstNum = 0;
int ratio = 0;
int repeats = 0;
printf("First number of the series: ");
scanf("%d", &firstNum);
printf("the ratio of the series: ");
scanf("%d", &ratio);
printf("the amount of numbers to display is ");
scanf("%d", &repeats);
forloop(firstNum,ratio,repeats);
}
void forloop(int firstNum,int ratio,int repeats)
{
int i = 0;
for (i=1; i!=repeats+1;i++)
{
printf("%d ", firstNum*(pow( ratio, i)));
}
}
This should fix the issue with printing zeros:
void forloop(int firstNum,int ratio,int repeats)
{
int i = 0;
for (i=1; i!=repeats+1;i++)
{
printf("%.0f ", firstNum*(pow((double)ratio,(double)i)));
}
}
As mentioned by #JonathanLeffler in the comments, you have a bug. The line
printf("%d ", firstNum*(pow( ratio, i)));
is wrong because pow returns a double but in the printf specifications %d expects an integer.
So, you can either change the specifier in your printf to a floating point one, i.e., %f, %g, %e, %F, %G, %E et cetera or cast pow's output to int by doing (int)pow(ratio, i).
In the first case, as #JadMrad said, if you are printing a double and you don't want to have decimal numbers, you can specify the number of digits at the right of the decimal point using "%.Nf" instead of "%f" where N is the number of decimal points that you want.
Nevertheless, in your case it seems to me that you are expecting always integer numbers. Then,
printf("%d ", firstNum*((int)pow( ratio, i)));
sounds like a better solution to me.
I wanted to create a program to calculate the regression line of some given data, along with the errors, so I can use in my university assignments. This is the following program:
#include <stdio.h>
#include <math.h>
int main(void)
{
int i,n,N;
double x[n],y[n],a=0.0,b=0.0,c=0.0,d=0.0,D,P=0.0,p,Sx,A,B,dA,dB;
printf("Give the number of data you want to input for x : ");
scanf("\n%d", &N);
printf("\nGive the values of x : ");
for (i=1; i<=N; i++);
{
printf("\n Enter x[%d] = ", i);
scanf("%lf", &x[i]);
a+=x[i];
b+=pow(x[i],2);
}
printf("\nGive the values of y : ");
for (i=1; i<=N; i++);
{
printf("\n Enter y[%d] = ", i);
scanf("%lf", &y[i]);
c+=y[i];
}
D=N*b-pow(a,2);
A=(b*c-a*d)/D;
B=(N*d-a*c)/D;
for (i=1; i<=N; i++);
{
d+=x[i]*y[i];
p=y[i]-A-B*x[i];
P+=pow(p,2);
}
Sx=sqrt(P/N-2);
dA=Sx*sqrt(b/D);
dB=Sx*sqrt(N/D);
printf("\n x \t \t \t y");
for (i=1; i<=N; i++);
printf("\nx[%d] = %lf\t%lf = y[%d]", x[i],y[i]);
printf("\nA = %lf\t B = %lf", A,B);
printf("\nThe errors of A & B are dA = %lf and dB = %lf", dA,dB);
printf("\nThe equation of the regression line is y=%lfx+(%lf)", B,A);
return 0;
}
I have two problems.
Despite giving a value to N, the program runs so that I can only give one value for x and one value for y. Why and where is the mistake?
When printing the "Enter x[%d]", it displays x[11] and at the end when printing "x[%d] = %lf\t%lf = y[%d]", it displays x[0]. Again why and where is the mistake?
Thank you for your help!
You are trying to create a dynamic array in C.
To do that, you need to use dynamic memory allocation with malloc and free. So, your code should look something like this:
int N;
double *x;
printf("Give the number of data you want to input for x :\n");
scanf("%d", &N);
x = malloc(sizeof(double) * N);
Then, at the end of your program you need to free the memory:
free(x);
If you don't want to deal with manual memory management (or can't for some reason), you can use a static maximum array size like this:
#define MAX_N_X 100
int main(void) {
int N;
double x[MAX_N_X];
printf("Give the number of data you want to input for x :\n");
scanf("%d", &N);
if (N > MAX_N_X) {
printf("Can't handle that many inputs! Maximum %d\n", MAX_N_X);
return 0;
}
}
You simply missed two parameters to printf.
Yo wrote:
printf("\nx[%d] = %lf\t%lf = y[%d]", x[i],y[i]);
But it should be:
printf("\nx[%d] = %lf\t%lf = y[%d]", i, x[i], y[i], i);
I found the main problem with this program a few days after posting this and the fix would be removing the ; from the for commands, along with some other minor changes. I thought I might add this comment to let you know and now it is working like a charm. The simplest of mistakes fools even the trained eyes. After I found this, I was shocked that no one picked up on this mistake.
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int mult;
int n;
int ans;
ans = mult * i;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 0; i<n; i++) {
printf("%d x %d = %d \n", &mult, &i , &ans);
}
return 0;
}
Hi guys, this is a simple code which is supposed to help the user to list the times table for n times. However, i am receiving undefined behaviour and I am quite stumped as to what is wrong with my implementation of my "for" loop.
I am receiving this as my output.
6356744 x 6356748 = 6356736
for n times in my consoles.
I want to ask
Is anything wrong with the logic of my code? (i assume i do have a problem with my code so please do enlighten me)
Would it be better(or even possible) to use pointers to point to the memory addresses of the mentioned variables when i have to change the value of the variables constantly? If yes, how do i go around doing it?
Thanks!
In printf you must provide integers. You are now giving the addresses of integers. So change
printf("%d x %d = %d \n", &mult, &i , &ans);
to
printf("%d x %d = %d \n", mult, i, ans);
and to make the table, replace ans with just mult*i, so:
printf("%d x %d = %d \n", mult, i, mult*i);
You should also check the return value of scanf to check if it has succeeded reading your input:
do {
printf("Please enter a multiple you want to explore.");
} while (scanf("%d", &mult)!=1);
do {
printf("Please enter the number which you would want to multiply this number till.");
} while (scanf("%d", &n)!=1);
The things you see are the values of the variables memory location.
Change your lines inside for loop as below
ans = mult * i;
printf("%d x %d = %d \n", mult, i, ans);
There are some mistakes in your code .
you are using the & operator in print statement which is used to print the address of the variable.
Initiate the loop with the value '1' instead of '0' & execute the loop till 'i' less than equal to 'n'.
instead of using the ans variable outside the loop , use it inside the loop as it evaluate the multiplication result in each iteration of the loop.
#include <stdio.h>
int main()
{
int i;
int mult;
int n;
int ans;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 1; i<=n; i++) {
ans = mult*i ;
printf("%d x %d = %d \n", mult, i , ans);
}
return 0;
}
I am very new to C, and while working on a project which requires pulling an indeterminate amount of values from the console, I am finding that it is not pulling the correct values. It seems like addresses, which I believe means it is a pointer issue, but I can't seem to find it.
int getVals(int degree){
double sum;
double x;
double coefs[degree];
for(int counter = 0; counter<=degree; counter = counter+1){
double nxt;
scanf(" %d", &nxt);
coefs[counter] = nxt;
printf("coefs[%d] = %d\n", counter, coefs[counter]);
}
printf(" x ? ");
scanf(" %d", &x);
printf("degree %d x %d\n", degree, x);
sum = poly(x, degree, coefs);
printf ("polynomial evaluate to: %lf\n", sum);
int newDegree;
scanf(" %d", &newDegree);
degree = newDegree;
if(degree>-1){
getVals(degree);
}
else
return degree;
}
Note: poly returns a double result of the evaluated polynomial
I am getting the following infinite loop after entering a degree of 1 and a coefficient of 1.5. It does not allow me to enter an x.
Infinite loop
In scanf(" %d", &newDegree); you should use the "%lf" format specifier (since your values is a double, not an int). Change the format specifier in all your calls to scanf() and "%f" in calls to printf().
Please refer to the documentation at this links printf(3), scanf(3).
I am trying to take user input, store it in an array for the number, and then take the dollars and cents portion of the numbers, store those in separate arrays, and then print the formatted number.
This is my code:
#include <stdio.h>
int main()
{
int i;
float amounts[5];
printf("Enter numbers as dollar amounts: \n");
for(i=0; i<5; i++) {
printf("Value %d: ", i+1);
scanf("%f", &amounts[i]);
}
long dollars[5];
long cents[5];
for (i=0; i<5; i++) {
dollars[i]=(int)amounts[i];
cents[i]=(amounts[i]-dollars[i]);
cents[i]*=100;
}
for (i=0; i<5; i++) {
printf("\n$%ld.", dollars[i]);
printf("%ld", cents[i]);
}
return 0;
}
I am somewhat unsure as to how I could take the cents and store them in an array as a long type. When executing the program, I get the correct dollars but the cents portion always comes out as 0. Any suggestions?
Edit:
So I attempted to solve some of the issues by doing this:
#include <stdio.h>
int main()
{
int i, j;
float amounts[5];
printf("Enter numbers as dollar amounts: \n");
for(i=0; i<5; i++) {
printf("Value %d: ", i+1);
scanf("%f", &amounts[i]);
}
long dollars[5];
long cents[5];
double decimal[5];
for (i=0; i<5; i++) {
dollars[i]=trunc(amounts[i]);
}
for (i=0; i<5; i++) {
printf("\n$%ld.", dollars[i]);
decimal[i]=100*(amounts[i]-dollars[i]);
cents[i]=(int)decimal[i];
if(cents[i]<10)
printf("0%ld", cents[i]);
else
printf("%ld", cents[i]);
}
return 0;
}
However, now I'm getting everything that is less than 10 for cents[i] to output 1 less than what it should be. So 3.06 prints as $3.05. The same for 3.12 for some reason.
Also, to some of the critique about what variable types I'm using, this is for an assignment and it dictates what types are to be used.
4 Write a program that will read five values from the keyboard (use a loop) and store them in an array of type float with the name amounts. Create two arrays of five elements of type long with the names dollars and cents. Store the whole number part of each value in the amounts array in the corresponding element of dollars and the fractional part of the amount as a two-digit integer in cents (e.g., 2.75 in amounts[1] would result in 2 being stored in dollars[1] and 75 being stored in cents[1]). Output the values from the two arrays of type long as monetary amounts (e.g., $2.75)
You're losing the fractional part here:
cents[i]=(amounts[i]-dollars[i]);
cents[i]*=100;
The difference between the two is less than 1, so assigning that value to an int results in it getting truncated to 0.
You need to multiply the difference before assigning to avoid truncation:
cents[i]=100*(amounts[i]-dollars[i]);
for (i=0; i<5; i++) {
dollars[i]=(int)amounts[i];
cents[i]=(amounts[i]-dollars[i]);
cents[i]*=100;
}
instead use:
for (i=0; i<5; i++) {
dollars[i]=(int)amounts[i];
double decimal = 100*(amounts[i]-dollars[i]);
cents[i]= (int)decimal;
}
OP's approach has problems
printf("\n$%ld.", dollars[i]);
printf("%ld", cents[i]);
Negative numbers amount[i] == -1.23 come out like "$-1.-23"
Values like amount[i] == 9.998 print as "$9.99" and likely should be "$10.00"
Missing leading zeros amount[i] == 1.03 print as "$1.3" #Jonathan Leffler
dollars[i]=(int)amounts[i] fails when amounts[i] is outside int range.
A key issue for OP
// problem
dollars[i]=(int)amounts[i];
cents[i]=(amounts[i]-dollars[i]); // cents[i] is an integer, cannot hold a fraction
cents[i]*=100;
// Alternative
// round
amount[i] = round(amount[i] * 100)/100.0;
// take apart;
float ipart;
cents[i] = (int) roundf(modff(amounts[i], &ipart)*100.0f);
dollars[i] = (int) ipart;
If code is to use FP for money recommend:
Use double.
Round to the nearest monetary unit after any calculation that is not exact. In OP's case this is 1/100.
amount[i] = round(amount[i] * 100)/100.0;
Use a unified print
printf("\n$%0.2f", amount[i]);
#include <stdio.h>
#include <math.h>
int main()
{
int i, j;
float amounts[5];
printf("Enter numbers as dollar amounts: \n");
for(i=0; i<5; i++) {
printf("Value %d: ", i+1);
scanf("%f", &amounts[i]);
}
long dollars[5];
long cents[5];
float ipart;
for (i=0; i<5; i++) {
cents[i] = (int) roundf(modff(amounts[i], &ipart)*100.0f);
dollars[i] = (int) ipart;
if(cents[i]==100){
dollars[i]++;
cents[i]=0;
}
}
for (i=0; i<5; i++) {
printf("\n$%ld.", dollars[i]);
if(cents[i]<10)
printf("0%ld", cents[i]);
else
printf("%ld", cents[i]);
}
return 0;
}