很抱歉,如果这是一个愚蠢的问题,我是C ++的新手。为什么不能正确地将所有输入复制到输出中?
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
using namespace std;
int main() {
int num1;
long num2;
long long num3;
char char1;
float num4;
double num5;
scanf("%d %ld %lld %c %f %lf", &num1, &num2, &num3, &char1, &num4, &num5);
//input: 211916801 452082285 97592151379235457 p 19856.992 -5279235.721231465
printf("%d %ld %lld %c %f %lf", num1, num2, &num3, &char1, &num4, &num5);
//expected output: 211916801 452082285 97592151379235457 p 19856.992 -5279235.721231465
//actual output: 211916801 452082285 68674564278975280 c 0.000000 0.000000
system("pause");
return 0;
}
答案 0 :(得分:5)
因为某些变量的&
不符合您的预期。
printf("%d %ld %lld %c %f %lf", num1, num2, &num3, &char1, &num4, &num5);
应该是
printf("%d %ld %lld %c %f %lf", num1, num2, num3, char1, num4, num5);
您的编译器应该已经警告过,因为您传递的值与格式说明符不匹配。如果没有,请打开/增加编译器警告。
答案 1 :(得分:4)
您应该将值本身而不是指针传递给printf
。
printf("%d %ld %lld %c %f %lf", num1, num2, num3, char1, num4, num5);
答案 2 :(得分:3)
在Printf(大多数情况下)你不使用&amp;在你的变量中。
printf("%d %ld %lld %c %f %lf", num1, num2, num3, char1, num4, num5);
另外,如果您是C ++的新手,可以采用更好的方式执行I / O操作。使用“cin”代替“scanf”和“cout”而不是“printf”
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
using namespace std;
int main() {
int num1;
long num2;
long long num3;
char char1;
float num4;
double num5;
//scanf("%d %ld %lld %c %f %lf", &num1, &num2, &num3, &char1, &num4, &num5);
cin >> num1;
cin >> num2;
cin >> num3;
cin >> char1;
cin >> num4;
cin >> num5;
//input: 211916801 452082285 97592151379235457 p 19856.992 -5279235.721231465
//printf("%d %ld %lld %c %f %lf", num1, num2, &num3, &char1, &num4, &num5);
cout << num1;
cout << num2;
cout << num3;
cout << char1;
cout << num4;
cout << num5;
//expected output: 211916801 452082285 97592151379235457 p 19856.992 -5279235.721231465
//actual output: 211916801 452082285 68674564278975280 c 0.000000 0.000000
system("pause");
return 0;
}
答案 3 :(得分:0)
使用printf(...)
时,原始类型按值传递,而不是通过引用传递。使用以下代码:
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
using namespace std;
int main() {
int num1;
long num2;
long long num3;
char char1;
float num4;
double num5;
scanf("%d %ld %lld %c %f %lf", &num1, &num2, &num3, &char1, &num4, &num5);
printf("%d %ld %lld %c %f %lf", num1, num2, num3, char1, num4, num5);
system("pause");
return 0;
}