2013-10-30 22 views
1

我无法在我的程序中找到正确的输出,以找出三个数字中的第二大数字。 (我知道这是非常基本的,但我刚刚开始学习C,所以任何帮助和提示将不胜感激!)在我的程序中,我得到了三个数字中的最大值和最小值(但没有问题),但我一直在第二大的答案204。 (这是错误的!)这是我的代码,对不起,如果有任何可怕的错误,就像我说的,我是新手!非常感谢! :)我一直得到不正确的输出为我的第二大号码程序(C程序)

//include the libraries 

#include <stdio.h> 

#include <conio.h> 

//include the main function 

int main() 
{ 

    //declare the variables 
    long a,b,c,min,max,secmax; 

    //read the variables 
    printf("a=");scanf("%ld",&a); 
    printf("b=");scanf("%ld",&b); 
    printf("c=");scanf("%ld",&c); 

    // Find the min of the 3 numbers. 
    if(b>a && c>a) 
    { 
     min=a; 
    } 
    else 
    { 
     min==b || min==c; 
    } 

    if(a>b && c>b) 
    { 
     min=b; 
    } 
    else 
    { 
     min==a || min==c; 
    } 

    if(a>c && b>c) 
    { 
     min=c; 
    } 
    else 
    { 
     min==a || min==b; 
    } 

    // Find the max of the 3 numbers. 

    if(b>a && b>c) 
    { 
     max=b; 
    } 
    else 
    { 
     max==a || max==c; 
    } 

    if(a>b && a>c) 
    { 
     max=a; 
    } 
    else 
    { 
     max==b || max==c; 
    } 

    if(c>a && c>a) 
    { 
     max=c; 
    } 
    else 
    { 
     max==a || max==b; 
    } 

    //Find the second largest number 
    if(a!=max && a!=min) 
    { 
     a=secmax; 
    } 
    else 
    { 
     b==secmax || c==secmax; 
    } 

    if(b!=max && b!=min) 
    { 
     b=secmax; 
    } 
    else 
    { 
     a==secmax || c==secmax; 
    } 

    if(c!=max && c!=min) 
    { 
     c=secmax; 
    } 
    else 
    { 
     b==secmax || a==secmax; 
    } 

    //print the output 
    printf("\nThe maximum is %d\n",max); 
    printf("\nThe second largest number is %d\n",secmax); 
    printf("\nThe minimum is %d\n",min); 

getch(); 

return 1; 
} 
+0

什么输入你给它?此外,这些代码块:'else { min == b ||分钟==℃; “对我没有意义。 – nhgrif

+0

我输入a = 3,b = 5和c = 8。好的,我应该把它们全部拿出来吗? :) – Eleanor

+0

基于'a = 3','b = 5','c = 8',它告诉你'204'是第二大的数字......? – nhgrif

回答

1

分配以这种方式工作:

... 
secmax = a; 
... 

这行代码分配给a​​。如果​​不包含任何内容(程序员行话中包含“垃圾”),则在执行此行后,它将等于a。这是你想要的。


a = secmax; 

这行代码是没有好处 - 它的,你想的正好相反。这可能是一个错字。


您的代码还存在其他问题,但这个问题似乎是最重要的问题;修复它后,您的代码有可能会运行。

0
// Find the min of the 3 numbers. 
if (b>a && c>a) 
{ 
    min = a; 
} 
else if(a>b && c>b) 
{ 
    min = b; 
} 
else 
{ 
    min = c; 
} 

这将正确设置分钟。您可以使用类似的逻辑/控制流程设置最大值,并根据最小/最大值计算出中间值。

+0

如果'a == b'和'c> a'那么你的代码不起作用。 – agbinfo

0

您需要做的第一件事是摆脱所有其他检查您目前有。他们只是评估布尔结果,而对他们无所作为。

其次,当你正在寻找第二大数量要指定secmax分为A,B & C,但实际上它应该是这样的:

if(a!=max && a!=min) 
{ 
    secmax = a; 
} 

if(b!=max && b!=min) 
{ 
    secmax = b; 
} 

if(c!=max && c!=min) 
{ 
    secmax = c; 
} 
相关问题