程序从用户那里收到一个正数k
,并应检查方程有多少解
3*x+5*y=k
在有许多解决方案的情况下,该函数采用所有解决方案中|x-y|
的更大的绝对值。如果只有一种解决方案,则将其打印出来。例如:
如果用户键入k=34
,则(x,y)
有两种解决方案:(3,5)
和(8,2)
。因此,程序有两种解决方案,分别计算|8-2|
和|3-5|
并采用较大的6。
如果示例的用户输入k=8
,则只有一个解决方案(1,1)
。
可悲的是,我的老师要求我只使用循环,if
和else
语句。没有递归,没有辅助函数,也没有数组。她还希望程序高效,这样我就不能在循环内部使用循环。
我试图编写代码,但是程序没有响应。我定义了counter
来计算方程的可能解数,并且distance
定义了更大的绝对值:
void check_how_many_solutions(int n) {
int y = 0, counter = 0, distance = 0, equation1 = 0, equation2 = 0, equation3 = 0;
while (equation3 <= n) {
equation1 = (n - (5 * y)) / 3;
equation2 = (n - (3 * equation1)) / 5;
equation3 = (3 * equation1) + (5 * equation2);
if (equation3 == n) {
counter++;
if (fabs(equation1 - equation2) > distance)
distance = fabs(equation1 - equation2);
}
y++;
}
if (counter > 1)
printf("The values of x and y are (%d,%d)\n", equation1, equation2);
else
printf("The greater absolute value of |x-y| is %d\n", distance);
}
代码可以运行,但是没有结果。
答案 0 :(得分:0)
这是我制作的一个程序,我相信它可以回答您所提出的问题。您只想遍历x的整数值,并检查计算出的y是否也是整数。我还跟踪找到的解决方案总数以及x和y之间距离最大的解决方案,并根据这些信息给出最终答案。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void count_solns(double);
int main(int argc, char *argv[])
{
if (argc == 2 && argv[1]) {
int k = atoi(argv[1]);
count_solns(k);
}
else {
puts("Usage: count_solns <positive_integer>");
return 1;
}
return 0;
}
void count_solns(double k)
{
printf("Print positive integer solutions to 3x + 5y = %.3f\n", k);
int solns_found = 0;
int distance = -1;
int final_x, final_y;
double x, y;
for (x = 0; x <= (k/3); x++) {
y = (k-3*x)/5;
if (y == floor(y)) {
printf("Solution found at (x, y) == (%d, %d)\n", (int) x, (int) y);
solns_found++;
if (fabs(x-y) > distance) {
final_x = x;
final_y = y;
}
}
}
if (solns_found == 0)
printf("No whole number solutions found for 3x + 5y = %.3f", k);
else if (solns_found == 1)
puts("This is the only solution where x and y are both whole numbers");
else
printf("The whole number solution with the highest distance between x and y is (x, y) == (%d, %d)", final_x, final_y);
return;
}
用法如下:
$ ./count_solns 70
Print positive integer solutions to 3x + 5y = 70.000
Solution found at (x, y) == (0, 14)
Solution found at (x, y) == (5, 11)
Solution found at (x, y) == (10, 8)
Solution found at (x, y) == (15, 5)
Solution found at (x, y) == (20, 2)
The solution with the highest distance between x and y is (x, y) == (20, 2)
答案 1 :(得分:0)
在查看max1000001的解决方案之前,我建议您先找到拧紧的位置,修复它,然后进行比较。
您的代码当前无限循环。尝试仅遍历代码的几次迭代并打印变量,然后查看它们对于每次迭代是否对您有意义。这是简化的相同代码,循环限制为20次迭代,并在每次迭代中打印变量:
void check_how_many_solutions(int n) {
int y = 0, counter = 0, distance = 0, equation1 = 0, equation2 = 0, equation3 = 0;
while( y < 20){
//while (equation3 <= n) {
equation1 = (n - (5 * y)) / 3;
equation2 = (n - (3 * equation1)) / 5;
equation3 = (3 * equation1) + (5 * equation2);
printf("y: %i, equation1: %i, equation2: %i, equation3: %i\n",y,equation1,equation2,equation3);
y++;
}
}