程序设计,我们的第一个家庭作业是取 4 个整数值,将最高的 2 加在一起,减去最低的 2,然后将结果平方。最后,比较这两个值,看看它们是否相等。
例如,如果您要输入:20 10 60 40
你会得到
60 + 40 = 100
和
20 - 10 = 10 --> 10^2 = 100
所以,100 == 100
我编写了我的程序并测试了各种值,这些值都返回了正确的结果。我的教授告诉我,我的程序在所有 10 个测试输入中都失败了,他把他得到的结果发给了我。他得到的结果和我的不一样,我也不知道是怎么回事。我给他发了电子邮件,他告诉我我的一个 for 循环的边界不正确。他是对的,但我仍然得到正确的结果,所以......?
这是代码,任何帮助将不胜感激!
/*
// Author: Jesse W
// Assignment 1
// Desciption:
// This program inputs four integer numbers a, b, c and d and
// determines if the sum of the two largest numbers is the same
// as the squared difference of the two smallest numbers
*/
#include <stdio.h>
/* Complete the code for this program below */
int main()
{
int a, b, c, d, f, k, swap;
int array_size = 4;
int return_val;
int sum, difference, square;
int small_1, small_2, large_1, large_2;
int array[array_size];
//Gather input
//printf("Enter integer values for a, b, c and d.\n");
return_val = scanf("%d %d %d %d", &a, &b, &c, &d);
//Validate input
if (return_val != 4)
{
printf("INVALID INPUT\n");
}
else
{
//Assign values to array
array[0] = a;
array[1] = b;
array[2] = c;
array[3] = d;
//Sort array
for (k = 0 ; k < ( array_size - 1 ); k++)
{
for (f = 0 ; f < array_size ; f++)
{
if (array[f] > array[f+1]) /* For decreasing order use < */
{
swap = array[f];
array[f] = array[f+1];
array[f+1] = swap;
}
}
}
//Assign sorted values to new variables
small_1 = array[0];
small_2 = array[1];
large_1 = array[2];
large_2 = array[3];
//Compute math
sum = large_1 + large_2;
difference = small_1 - small_2;
square = difference * difference;
//Compute logic
if(sum == square)
{
printf("%d equals %d.\n", sum, square);
}
else
{
printf("%d does not equal %d.\n", sum, square);
}
return 0;
}
}