c - 添加两个整数变量并显示输出 C

标签 c printf undefined-behavior format-specifiers

我正在尝试用 C 语言创建一个简单的程序,它添加了两个数字变量。 我试图验证输入,但现在程序不显示答案,只是 0.000000000

 #include<stdio.h>
int input, temp, status, numberOne, numberTwo, ans;

int main(void){

first();
second();
add();
}


int first(void){
    printf("Please enter your number: ");
    status = scanf("%d", &input);
    while(status!=1){
        while((temp=getchar()) != EOF && temp != '\n');
        printf("Invalid input... please enter a number: ");
        status = scanf("%d", &input);

    }
    numberOne = input;
}

int second(void){
    printf("Please enter your second number: ");
    status = scanf("%d", &input);
    while(status!=1){
        while((temp=getchar()) != EOF && temp != '\n');
        printf("Invalid input... please enter a number: ");
        status = scanf("%d", &input);
        }
    numberTwo = input;
}

int add(void){
    ans=numberOne+numberTwo;
    printf("The answer is %f", ans);
}

最佳答案

结果应该有一个 %d 格式说明符而不是 %f

printf("The answer is %d", ans);

注意:- %d 格式说明符用于整数,%f 通常用于 float 。

在您的情况下,您将使用以下代码获取两个输入整数:

status = scanf("%d", &input);

所以这里的%d表示这两个数都是整数。现在添加它们将给出整数结果。因此,您应该仅使用 %d 来获取结果。

关于c - 添加两个整数变量并显示输出 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29029333/

相关文章:

c++ - 悬空引用和未定义行为

c - C语言中的 "expression"是什么意思?

c - sprintf 在 C 中前导零填充

c++ - 将 xvalues 转换为 lvalues 以传递给函数是否定义明确?

c - 在 C 中使用指向 typedef 类型的指针作为指向原始类型的指针是未定义的行为吗?

c - fprintf 给我一个 c 中的空白文件

c - 为什么-x[ptr]总是0?

c - C 中的三元运算符和 Return

c - 在 C++/CLI 中访问非托管数组

python - printf 样式格式字符串的解析器