我在我的数组00,11,22,33
中存储了四个数字。当我生成一个随机数并打印它时,它会显示0
而不是00
(当选择第一个元素时)。其他数字很好,显示正确。如何在阵列中存储00以便正确显示?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int myArray[4] = { 00,11,22,33 };
int randomIndex = rand() % 4;
int randomIndex1 = rand() % 4;
int randomIndex2 = rand() % 4;
int randomIndex3 = rand() % 4;
int randomValue = myArray[randomIndex];
int randomValue1 = myArray[randomIndex1];
int randomValue2 = myArray[randomIndex2];
int randomValue3 = myArray[randomIndex3];
printf("= %d\n", randomValue);
printf("= %d\n", randomValue1);
printf("= %d\n", randomValue2);
printf("= %d\n", randomValue3);
return(0);
}
答案 0 :(得分:2)
0
数字与11
数字完全相同,而1
显然与00
不同。
考虑存储字符串。或者,如果您想显示%02d
,则使用printf("= %02d\n", randomValue);
作为格式字符串只需2个字符:
int myArray[4] = {0,1,2,3};
. . .
printf("= %d%d\n", randomValue, randomValue);
如果这真的是你的整个程序,你甚至可以修改你的数组,然后两次打印值:
import {User} from '../model';
export class DrawingSocket {
connectedUsers = [];
drawingConnection: any;
constructor(private socketIO: any) {
this.socketIO.of('/sockets/drawing').on('connection', (con: any) => {
this.drawingConnection = con;
this.listen();
});
console.log("Drawing socket listening at /sockets/drawing/");
}
private listen(): void {
this.drawingConnection.on("drawing", (data: any) => {
console.log("[DRAWING] Room "+data.room);
this.drawingConnection.to(data.room).emit("draw", data);
});
this.drawingConnection.on("clear", (data: any) => {
console.log("[DRAWING] CLEAR for room "+data.room);
this.drawingConnection.to(data.room).emit("clear", data);
});
this.drawingConnection.on("login", (user: any) => {
this.drawingConnection.join(user.room);
this.connectedUsers[user._id] = user;
this.drawingConnection.to(user.room).emit("userlist", this.getSimpleUserList());
this.drawingConnection.emit("userlist", this.getSimpleUserList());
console.log("User " + user.name + " joined room " + user.room);
console.log(JSON.stringify(this.socketIO.rooms));
});
this.drawingConnection.on("logout", (user: any) => {
var room = this.connectedUsers[user._id].room;
this.drawingConnection.to(room).emit("userlist", this.getSimpleUserList());
this.drawingConnection.leave(room);
console.log("User " + user.name + " disconnecting from room " + room + ".");
});
this.drawingConnection.on("disconnect", () => {
//leave room and such
});
}
private getSimpleUserList() {
let list = this.connectedUsers.map((user) => user.login);
return list;
}
}
答案 1 :(得分:0)
%02d
扫描代码将打印零填充的随机数:
printf("%02d\n", randomValue);
// Expected output for 0: 00
^
This 0 belongs to the scan code
此外,%2d
扫描代码将为您执行空格填充:
printf("%2d\n", randomValue);
// Expected output for 0: 0
^
This space belongs to the scan code
一般来说,%(0)NM
是一个扫描码,其中包含:
0
是可选的,它属于数字,如果使用它,它将向输出添加零填充;如果没有使用它,它将添加空格填充。
N
是您要打印的位数/字符数,例如2
。
M
是您要显示数据类型的扫描代码,例如{d, x, c, s, ...}
代表{number, hexadecimal number, character, string, ...}
您可以找到完整的扫描代码列表here。