[英]I'm trying to execute this code on Vscode but whenever I'm running this it's not taking the value of character but just showing a random number
我是在线编码和学习 C++ 的新手,但是在运行此代码时,它只是不采用字符的值。 如果使用cin
或 cout 它工作正常,但scanf
给我带来了问题。 有人可以以最基本的方式向我解释我做错了什么吗
#include<iostream>
#include<cstdio>
#int main(){
int num1, num2;
char oper;
printf("The first number is: ");
scanf("%d", &num1);
printf("The second number is: ");
scanf("%d", &num2);
printf("The operation you want to perform is: ");
scanf("%c", &oper);
if(oper == '+'){
int total= num1+num2;
printf("%i", &total);
}
else if(oper == '*'){
int mul= num1 * num2;
printf("%d", &mul);
}
else{
int diff = num1-num2;
printf("%d", &diff);
}
return 0;
}
#
在int main()
之前。%d
在读取的数字后留下换行符,如果存在, %c
将读取它。 您应该在%c
之前添加一个空格字符以使其具有scanf()
空白字符(包括换行符)以使其忽略空格字符。printf()
中的%i
和%d
需要int
。 在那里传递int*
会调用未定义的行为。固定代码:
#include<iostream>
#include<cstdio>
int main(){ // remove extra #
int num1, num2;
char oper;
printf("The first number is: ");
scanf("%d", &num1);
printf("The second number is: ");
scanf("%d", &num2);
printf("The operation you want to perform is: ");
scanf(" %c", &oper); // add a space
if(oper == '+'){
int total= num1+num2;
printf("%i", total); // pass the number itself, not a pointer
}
else if(oper == '*'){
int mul= num1 * num2;
printf("%d", mul); // pass the number itself, not a pointer
}
else{
int diff = num1-num2;
printf("%d", diff); // pass the number itself, not a pointer
}
return 0;
}
此外,如果您添加一些代码来检查scanf()
的返回值以检查它们是否成功读取预期内容,您的代码也会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.