My problem is, I'm doing some practice while I'm sick and I don't go to school and I ran into a problem which I was solving whole last night, but looks so simple yet it is complicated, so here's the problem: /*Write a program where the user will load the three-digit integer and sums all digits of the number and calculates a mystery number with the following equation:
mn = round((a^3+ b^2+c^ )/(a+2*b+3*c))
, where a
is the first digit, b
is the second digit and c
is the third digit
In the first line of the console must be the sum of the digits and in the second has to be the mystery number.*/
And here's where I got the problem, no matter how many times I try it just prints that mystery number is 0, but the sum is alright, although I could write the code a bit better here's the code:
#include <math.h>
#include <stdio.h>
int main(){
int n;
int a, b, c, sum;
double mn;
printf("n = ");
scanf("%d", &n);
a = (n / 100);
b = (n / 10) - a * 10;
c = n - a * 100 - b * 10;
sum = a + b + c;
mn = round((a^3 + b^2 + c) / (a + 2 * b + 3 * c));
printf("\nmn = %f", mn);
printf("\nsum is = %d", sum);
return 0;
For this code I used stdio.h and math.h. Help me. Please.
In mn = round((a^3 + b^2 + c) / (a + 2 * b + 3 * c));
:
^
is not exponentiation; a^3
does not calculate the cube of a
. (a^3 + b^2 + c)
and (a + 2 * b + 3 * c)
are integer expressions, so /
performs integer division, which truncates. To calculate simple powers of integer values, simply multiply them as needed, such as a*a*a
and b*b
.
To perform floating-point division instead of integer division, convert either of the operands to double
, as with (double) (a*a*a + b*b + c)
.
您将方程的结果分配给tb并打印mn ,它从未初始化并且可能将 0 作为其默认值。
You don't seem to store anything in variable mn, instead I see you're using a variable named tb for you mystery number calculation. I also second the fact that the ^operator doesn't do exponentiation, it is a bitwise xor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.