69,512
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
计算letters:
int i=0;
while (name[i]!='\0')
{
letters++;
i++;
}
name的数据类型声明不对,不应该是char,应该是字符数组。
把第8行改为:
char name[10];
数组元素个数设置为允许接收的最大字符数,我举的例子是10。
抽空给你写的新版
#include <stdio.h>
#include <string>
#include <iostream>
#define DENSITY 62.4
using namespace std;
int main() {
float weight, volume;
int name_length = 0;
string name;
char c;
printf("Hi! what's your first name?\n");
getline(cin, name);
for (char i: name)
if (i != ' ') name_length++;
printf("%s, what's your weight in pounds? \n", name.c_str());
scanf("%f", &weight);
for (char i: name) {
c = name[i];
if ((c < 48 || c > 57 )&& c != 46) {
printf("Sorry %s, please enter the correct digit.\n", name.c_str());
return 0;
}
}
volume = weight / DENSITY;
printf("well,%s,your volume is %2.2f cubic feet.n", name.c_str(), volume);
printf("Also,your first name has %d letters, \n", name_length);
printf("and we have %lu bytes to store it.\n", sizeof(name));
getchar();
return 0;
}
而且名字可能会有空格,所以在这里scanf()函数可能不太合适
我建议你定义一个string类型的来存名字,因为大多数名字是有多个字的
我给你的代码更改了一下
#include <stdio.h>
#include <string.h>
#define DENSITY 62.4
using namespace std;
int main() {
float weight, volume;
int size, letters;
char name;
printf("Hi! what's your first name?\n");
scanf("%s", &name);
printf("%c, what's your weight in pounds? \n", name);
scanf("%f", &weight);
size = sizeof(name);
volume = weight / DENSITY;
printf("well,%c,your volume is %2.2f cubic feet.n",name, volume);
printf("Also,your first name has %d letters, \n", letters);
printf("and we have %d bytes to store it.\n", size);
getchar();
return 0;
}