c - 显示 4 个整数中的最大值和最小值,同时显示它们的位置
问题描述
这是我在大学学习 Comp-Sci 课程的第一年,在这门课程之前我没有任何编程经验。我目前正在尝试为类分配编写一个 C 程序,该程序接受 4 个整数输入,然后显示 4 个中的最大和最小,同时还说明输入最大和最小整数的位置。
注意:我不允许使用任何函数、数组或循环(除了下面给出的 while 循环,但仅此而已)。
我的教授提供了一个大纲来帮助入门。
这是我的代码:
#include <stdio.h>
int main(void)
{
int x1, x2, x3, x4;
int xlarge, xsmall, ixlarge, ixsmall;
while (1)
{
printf("enter x1, x2, x3, x4:\n");
scanf("%d%d%d%d", &x1, &x2, &x3, &x4);
/* add code to calculate xlarge, xsmall,
* ixlarge, ixsmall
* --> between here */
if ((x1 > x2) && (x1 > x3) && (x1 > x4))
x1 = xlarge;
else if ((x2 > x1) && (x2 > x3) && (x2 > x4))
x2 = xlarge;
else if ((x3 > x1) && (x3 > x2) && (x3 > x4))
x3 = xlarge;
else if ((x4 > x1) && (x4 > x2) && (x4 > x3))
x4 = xlarge;
if ((x1 < x2) && (x1 < x3) && (x1 < x4))
x1 = xsmall;
else if ((x2 < x1) && (x2 < x3) && (x2 < x4))
x2 = xsmall;
else if ((x3 < x1) && (x3 < x2) && (x3 < x4))
x3 = xsmall;
else if ((x4 < x1) && (x4 < x2) && (x4 < x3))
x4 = xsmall;
if (xlarge = x1)
ixlarge = 1;
else if (xlarge = x2)
ixlarge = 2;
else if (xlarge = x3)
ixlarge = 3;
else if (xlarge = x4)
ixlarge = 4;
if (xsmall = x1)
ixsmall = 1;
else if (xsmall = x2)
ixsmall = 2;
else if (xsmall = x3)
ixsmall = 3;
else if (xsmall = x4)
ixsmall = 4;
/* <-- and here */
printf("largest = %4d at position %d, ", xlarge, ixlarge);
printf("smallest = %4d at position %d\n", xsmall, ixsmall);
}
while (1) getchar();
return 0;
}
据我了解,如果该程序满足条件,则应将其分配xlarge
给xsmall
输入,对于ixlarge
and 也是如此ixsmall
。但是,我在尝试运行该程序时遇到的一个问题是,xlarge
显然xsmall
没有初始化,我不知道从哪里开始。
解决方案
看代码:
它应该是xlarge = x1
而不是x1 = xlarge
类似地xsmall = x1
,因为它是 xlarge 存储 x1 的值,而不是相反。
你也可以像这样使用你的 if-else:
if ((x1 > x2) && (x1 > x3) && (x1 > x4))
{
xlarge = x1;
ixlarge = 1;
}
else if ((x2 > x1) && (x2 > x3) && (x2 > x4))
{
xlarge = x2;
ixlarge = 2;
}
等等...
推荐阅读
- sql - 从逗号分隔和 ID 列创建 Excel 查找表工作表
- r - 如何将条形图更改为线图
- ios - AlamoFire POST 请求使用 Swift 给我一个错误
- ruby-on-rails - 从 Capybara 中查找 css 内容中指定的图像 url
- python-3.x - 附近和文本搜索零结果
- batch-file - 在目录中运行可执行命令的批处理文件
- jquery - 如何使用ajax填充html
- sql-server - SQL 完整备份作业执行时间过长
- bash - 如何在 unix shell 脚本中读取和打印 Ansible set_fact 数组
- java - 为什么lookArounds的lookAround返回true,而匹配返回false