Tôi mới với lập trình C, và tôi đã viết mã này như tôi đã được yêu cầu làm một cái gì đó bằng cách sử dụng chủ yếu printf() và scanf(). Tôi biết có thể có những cách tốt hơn để xử lý này, mà tôi sẽ cần phải học sớm, nhưng dù sao, bây giờ đây là những gì tôi có:Tại sao pow() trừ 1 từ kết quả của tôi?
int add1, add2, exponent, exponent_result, multiplier, parenthese, product, sub, total;
printf("Let's try a slightly more complex calculation, in which we'll use an exponent.\n\n");
printf("Type 5 whole numbers or integers.\n\n");
scanf("%i %i %i %i %i", &add1, &add2, &exponent, &multiplier, &sub);
printf("Out of the numbers you typed, we're going to make this operation: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub);
exponent_result = pow(add2, exponent);
parenthese = add1 + exponent_result;
product = parenthese * multiplier;
total = (add1 + exponent_result) * multiplier - sub;
printf("Per PEMDAS, the correct order of operation is Parentheses, then Exponents, then Multiplications and Divisions, and finally Additions and Subtractions.\n\n");
printf("Therefore: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub);
printf("...is equal to: (%i + %i) * %i - %i\n\n", add1, exponent_result, multiplier, sub);
printf("...is equal to: %i * %i - %i\n\n", parenthese, multiplier, sub);
printf("...is equal to: %i - %i\n\n", product, sub);
printf("...is equal to: %i", total);
Nếu bạn chạy mã này, bạn sẽ nhận ra rằng đầu ra cho exponent_result, được tính toán bằng cách sử dụng pow() function
, luôn luôn có 1 trừ từ nó. Ví dụ: nếu exponent_result được cho là kết quả của 5^3
, kết quả cho điều đó sẽ là 124
thay vì 125
.
Tôi đang làm gì sai?
Fyi, tôi có điều này ở đầu tệp của mình.
#include <stdio.h>
#include <math.h>
Bạn đã kiểm tra sự cố của mình chưa. Như trong khi tôi đã cố gắng để chạy chương trình của bạn nó làm việc tốt. Không có vấn đề gì. Nếu bạn vẫn gặp sự cố khi chia sẻ mã runeable ide trực tuyến để chúng tôi có thể kiểm tra vấn đề. Tôi nhận được kết quả phù hợp. Bạn có muốn nói rằng đầu vào những gì bạn đã đặt đang có vấn đề nhất định? –
không cố gắng sử dụng phao atirthmetics để tính toán số nguyên. Số nguyên luôn luôn chính xác, phao nổi hầu như không luôn luôn. I –
Tránh cắt xén, thay vào đó thay vì 'exponent_result = lround (pow (add2, exponent));' – chux