函数在其之前调用另一个函数时返回不同的值

时间:2014-09-17 01:07:16

标签: c function

标题几乎说明了一切。但我正在运行一个字符编码功能,该功能从基于输入的班次的值转移。这个函数运行正常,但是如果调用它上面的函数,则每次返回“Ω”。

的main.c

int main()
{
    assignment3();
    assignment5();
    return 0;    
}

equations.c

int assignment4(void)
{
    int res1=0, res2=0, res3=0;
    float parallel_resistance=0;

    printf("Please enter the resistance for three resistors: ");
    scanf("%d%d%d",&res1,&res2,&res3);// takes user input for 3 resistances
    parallel_resistance=calculate_parallel_resistance(res1,res2,res3);
    printf("The parallel resistance is: %.2lf\n\n",parallel_resistance);
    return 0;
}

int assignment5(void)
{
    char plaintext_character='\0',encoded_character='\0';
    int shift=0;
    printf("Please enter a character(a - z) and an integer: ");
    scanf("%c%d",&plaintext_character,&shift);//takes and assigns the user inputs to the                        variables
    encoded_character=preform_character_encoding(plaintext_character,shift);
    printf("The newly created character is now: %c\n\n",encoded_character);
    return 0;
}

这些来自上面函数中包含的头文件

char preform_character_encoding(char plaintext_character,int shift_key)
{
    char encoded_character='\0';
    encoded_character=(plaintext_character-'a')+'A' - shift_key; // calculates the new character
    return encoded_character;
}

double calculate_volume_pyramid (double length, double width, double height)
{
    double volume=0,lwh=0;
    lwh=(double)(length*width*height); // calculates the volume using the inputs
    volume=lwh/3.0;
    return volume;
}

1 个答案:

答案 0 :(得分:1)

从标准输入中读取字符时需要非常小心:使用%c格式,因为scanf会返回碰巧在缓冲区中首先出现的任何字符,包括不可打印的字符。在这种情况下,看起来assignment4在缓冲区中留下悬空\n。这就是%c进入assignment5的角色。

你应该添加一个循环来读取字符,丢弃空格和特殊字符,如下所示:

do (
    scanf("%c", &plaintext_character);
} while (c == ' ' || c == '\n');
scanf("%d", &shift);
相关问题