此代码://无需添加评论
int main(){ //no comment to add
//no comment to add
//no comment to add
float x[2] = {1,2}; //array 1
float y[2] = {5,7 }; //array 2
float* total = (float*)malloc(4 * sizeof(float)); // array to hold the result
//no comment to add
memcpy(total, x, 2 * sizeof(float)); // copy 2 floats from x to //total[0]...total[1]
memcpy(total + 2, y, 2 * sizeof(float)); // copy 2 floats from y to //total[2]...total[3]
//no comment to add
//no comment to add
for(int i=0;i<4;i++){ //no comment to add
printf("the value for total[%d] is %d\n",i,total[i]); //copy arrays //x,y into the 'total' array.
} //no comment to add
返回0; //无需添加评论 } //没有评论要添加
///-----------------------------------------
/// gives the result:
/// the value for total[0] is 0;
/// the value for total[1] is 0;
/// the value for total[2] is 0;
/// the value for total[3] is 0;
/// and i want to get:
/// the value for total[0] is 1;
/// the value for total[1] is 2;
/// the value for total[2] is 5;
/// the value for total[3] is 7;
/// Can someone give the correct code??
//无评论添加
答案 0 :(得分:1)
printf
%d
使用了错误的格式说明符float
。
您必须%f
使用float
或double
。
printf("the value for total[%d] is %f\n",i,total[i]);
程序输出现在是
the value for total[0] is 1.000000
the value for total[1] is 2.000000
the value for total[2] is 5.000000
the value for total[3] is 7.000000
答案 1 :(得分:0)
如果你只需处理整数,我建议将所有浮点数替换成int:
int main()
{
int x[2] = {1,2};
int y[2] = {5,7};
int* total = (int*)malloc(4 * sizeof(int));
memcpy(total, x, 2 * sizeof(int));
memcpy(total + 2, y, 2 * sizeof(int));
for(int i=0;i<4;i++)
{
printf("the value for total[%d] is %d\n",i,total[i]);
}
free(total);
return 0;
}